【问题标题】:Comparing user input to an array of Strings将用户输入与字符串数组进行比较
【发布时间】:2013-12-04 09:19:42
【问题描述】:

我必须将用户输入的内容与名称数组进行比较,如果为真,则返回真,否则返回假,到目前为止我有这个

public static boolean employeeReport(Employee[] emp, String[] lastName) throws IOException
{
    System.out.println("Type out the last name of the employee you are looking for: ");
    Scanner scan = new Scanner (System.in);
    String Name = scan.next();

    // ...
}

我正在考虑创建一个 for 循环并将“名称”与我拥有的字符串数组的每个单独值进行比较。有什么帮助吗?

【问题讨论】:

  • 也许您应该提及您使用的语言!?

标签: java arrays if-statement for-loop equals


【解决方案1】:

将所有员工的姓名插入到

Set<String> set

然后检查一下

set.contains(name) //return true if exists and false if not

【讨论】:

    【解决方案2】:

    假设您有一个包含员工姓名的字符串数组,例如:

    String[] nameBook;
    

    你可以这样做:

    public static boolean employeeReport(Employee[] emp, String[] lastName) throws IOException
    {
        System.out.println("Type out the last name of the employee you are looking for: ");
        Scanner scan = new Scanner (System.in);
        String name = scan.next();
    
        //loop through the array and compare against entered name
        for(String n : nameBook) {
            if (n.equals(name)) return true;
        }
    
        return false;  
    }
    

    请注意,按照 Java 约定,变量名应以小写字母开头(我已在您的代码中更正了它)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2016-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多