将用户输入与字符串数组进行比较

时间:2013-12-04 09:19:42

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

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

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循环并将“Name”与我拥有的String数组的每个单独值进行比较。有什么帮助吗?

2 个答案:

答案 0 :(得分:0)

将所有员工姓名插入

Set<String> set

然后只需检查

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

答案 1 :(得分:0)

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

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约定,变量名称应以小写字母开头(我已在您的代码中对其进行了更正)。