2016-02-26 83 views
0

一直在我的頭上靠近牆壁......可能與晚點有關,但是我的while循環不會在我輸入變量「count 「第三次。代碼如下:count ++:while()在計數達到後不會停止循環

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循環,只是由於某種原因,它不會停止循環一次「計數」達到3理解固。 有沒有我可以忽略的東西?

非常感謝 薩姆

回答

1

不嵌套的循環中使用布爾和條件,一個循環。類似的,

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

爲了進一步解釋,內循環將繼續運行,直到輸入正確的密碼。因此即使'count'可能會大大增加3,外循環也不會完成迭代,直到輸入正確的密碼並允許內循環終止。 –

+0

非常感謝您的解釋。 –

0

這是因爲inner 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++; 
+0

非常感謝!我得到它的工作。 –