将用户的String输入与String数组进行比较

时间:2014-03-26 21:43:27

标签: java arrays string methods

我知道这是一个非常小而且愚蠢的东西,但我不知道为什么这不起作用。基本上只有两个员工名称可用于登录。这两个名称存储在一个数组中。一旦用户输入了名称并且它不是两个正确的名称之一,程序就会一直询问用户名。

String [] userNames = {"Jack", "Jill"};  
logIn(userNames);

public static void logIn(String [] name)
{
    String userName = "";
    Scanner kb = new Scanner(System.in);
    System.out.print("Enter Username: ");
    userName = kb.nextLine();
    while (userName != name[0] || userName != name[1])
    {
        System.out.print("Enter Username: ");
        userName = kb.nextLine();
    }
    System.out.println("Correct");
}

1 个答案:

答案 0 :(得分:1)

要比较字符串,应使用equalscompareTo

String [] userNames = {"Jack", "Jill"};  
logIn(userNames);

public static void logIn(String [] name)
{
    String userName = "";
    Scanner kb = new Scanner(System.in);
    System.out.print("Enter Username: ");
    userName = kb.nextLine();
    //while (userName != name[0] || userName != name[1])
    while (!userName.equals(name[0]) && !userName.equals(name[1]))
    {
        System.out.print("Enter Username: ");
        userName = kb.nextLine();
    }
    System.out.println("Correct");
}