count ++:while()在达到计数后不会停止循环

时间:2016-02-26 05:58:59

标签: java loops netbeans while-loop

在这里,我的头撞到墙上......可能与已故的时间有关,但是一旦我输入了变量,我的while循环就不会结束了#34;计数"第三次。代码如下:

Scanner input = new Scanner(System.in);

        final String CORRECT_PASSWORD = "CS1160";
        String password;
        int count = 0;

       //ask for password

        System.out.println("Please enter your password: ");      
        password = input.nextLine();

        if(password.equals(CORRECT_PASSWORD)){
           System.out.println("You have successfully logged in.");
                                             }

       count = 0;
    while(count < 3){
        while(!password.equals(CORRECT_PASSWORD))
         {
           System.out.println("Incorrect Password Entered.");
           System.out.println("Please enter your password: ");
           password=input.nextLine();
           count++;

        if(password.equals(CORRECT_PASSWORD)){
           System.out.println("You have successfully logged in.");

           count++;   
         }}



        }
        System.out.println("You have been locked out.");
        }}

___________________ END _______________________

  • 一切都很好......从我对while循环的理解看起来很稳定,只是出于某种原因它不会停止循环一次&#34; Count&#34;达到三。 是否有我可以忽略的东西?

非常感谢 -SAM

2 个答案:

答案 0 :(得分:1)

不要嵌套循环,使用布尔和条件以及一个循环。像,

while(count < 3 && !password.equals(CORRECT_PASSWORD))

答案 1 :(得分:0)

这是因为内在的while循环。在你没有提供正确的密码之前,它不会出现在那里。使用单个while循环,例如:

while(count < 3 && !password.equals(CORRECT_PASSWORD))

然后在这里,你应该写:

System.out.println("Please enter your password: ");
           password=input.nextLine();
           count++;

        if(password.equals(CORRECT_PASSWORD)){
           System.out.println("You have successfully logged in.");
           break;//brings you out of the while loop as you don't need to check for the password again.
         }

           count++;