而/ if语句导致无限循环,正确的输入读错

时间:2017-04-19 01:11:30

标签: java loops

我正在为我的java课程开始我的最终项目,并且我在开放时遇到了一些问题。我需要使用用户名&进行授权屏幕密码,每个用户都有一个特定的屏幕,可以使用它们的组合进行访问。

我一直专注于第一个用户名/密码,因为我知道正确的用户名/密码将使其余的更容易。但是,当我输入正确的密码时,读取的用户名被修正后,会出现“错误登录”循环,然后即使在输入正确的密码后也会进入无限循环。

我已经包含了以下代码。我已经设置了导入java.util.Scanner。

    Scanner scnr = new Scanner (System.in);
    String userName = "";
    String userPassword = "";

    System.out.println("Enter username: ");
    userName = scnr.next();

    while (userName.equals("griffin.keyes")) {       //multiple users names
        System.out.println("Enter password: ");      //easier method?
        userPassword = scnr.next();                  //to be looked into
        if (userPassword.equals("alphabet soup")){
            System.out.println("Hello, Zookeeper!"); //broken up to increase readability
            System.out.print("As zookeeper, you have access to all");
            System.out.print(" of the animals' information and their");
            System.out.print("daily monitoring logs. This allows you to");
            System.out.print(" track their feeding habits, habitat");
            System.out.println(" conditions, and general welfare.");
        }
        else {
            System.out.println("Login failed");     //needs to be fixed
            System.out.println("Enter password: "); //needs to repeat three times
            userPassword = scnr.next();             //issue with while statement?
        }
    }
}

3 个答案:

答案 0 :(得分:0)

问题是你的状况总是如此。用户名永远不会改变,因此它会继续循环。如果您正在尝试读取包含空格的行,也可以使用scnr.nextLine(),因为next()一次只读取一个标记,而不是您想要多字密码的整行。

答案 1 :(得分:0)

while条件下,userName.equals("griffin.keyes")将始终为真,因为变量userName未被修改。

您可能需要将您的while条件更改为

while (numOfRetries <= MAX_ALLOWED) {
   ... do the logic
   numOfRetries++; // when password fails
}

答案 2 :(得分:0)

您的用户名永远不会更改,因此while (userName.equals("griffin.keyes"))while (true))相同。有一些解决方法,这里有一个:

int reties=3;
while (userName.equals("griffin.keyes")&&retires!=0) {       //multiple users names (keep condition like this)
    System.out.println("Enter password: ");      //easier method?--Not sure what that means
    userPassword = scnr.next();                  //to be looked into
    if (userPassword.equals("alphabet soup")){
        System.out.println("Hello, Zookeeper!"); //broken up to increase readability
        System.out.print("As zookeeper, you have access to all");
        System.out.print(" of the animals' information and their");
        System.out.print("daily monitoring logs. This allows you to");
        System.out.print(" track their feeding habits, habitat");
        System.out.println(" conditions, and general welfare.");
        break;
    }
    else {
        System.out.println("Login failed");     //Fixed
        System.out.println("Enter password: "); //3x Done 
        userPassword = scnr.next();             
        retries--;
    }
}

或者你可以修改你的while条件以便更好地适应它并在while循环之外拥有zookeeper的工作细节(这取决于你想要如何接近它)。