2017-09-13 808 views
0

我正在爲類進行分配,並希望創建一個循環,爲用戶提供3次登錄機會,輸入正確的用戶名和密碼。Java:while循環輸入用戶名和密碼3次 - 用break語句發出?

  • 成功時,給消息「您現在已經在」

  • 當輸入錯誤的1-2倍,給予信息「輸入錯誤,重試(...)」,然後提示輸入用戶名和密碼再次

  • 當輸入錯誤3次,給消息「你輸入3次錯誤(...)」,然後退出系統

這裏是我的代碼的一部分:

System.out.println("Enter password"); 
String inputPassword = input.next(); 

int count = 0; 

//create while loop, set loop continuation condition to count < 3 
while (count <= 2) {    

    if ((!inputUsername.equals(userName)) || (!inputPassword.equals(password))) {  
     System.out.println("Wrong entry. try again: Enter username"); 
     inputUsername = input.next(); 

     System.out.println("Enter password"); 
     inputPassword = input.next(); 
    } 
    else 
     System.out.println("You are now logged in");  

    count++; 

    break; 
} 

if (count > 2) 
System.out.println("You have enterede wrong three times. Please try again in a few hours"); 
System.exit(0); 

爲什麼系統退出後2失敗,沒有給我錯誤消息的嘗試「你輸入3次錯誤(......)」你知道嗎?

我認爲問題出在增加計數後的「中斷」,但不確定。

如果沒有這個中斷,在成功輸入的情況下,控制檯會顯示「您現在已登錄」3次,然後顯示錯誤消息「您輸入錯誤三次(...)」 - 這就是爲什麼我要它。

回答

0

您的break是無條件的。它會一直運行,這意味着你的循環總是會在第一次迭代時退出。

前兩次失敗嘗試都發生在第一次迭代之前和期間,然後您點擊break並退出。既然你從來沒有打過架,count只會在打破之前增加一次。

我相信你打算使用大括號將break分組在else下。現在,由於您不使用花括號,因此只有println聲明是else的一部分。 永不遺漏花括號

0

謝謝Carcigenicate!

這很有道理!

我同時找到了解決方案。我已經改變了延續條件,它的工作原理!

int count = 0; 

//create while loop, set loop continuation condition to count <2 
while (count < 2 && ((!inputUsername.equals(userName)) || (!inputPassword.equals(password)))) { 
    System.out.println("Wrong entry. try again: Enter username"); 
    inputUsername = input.next(); 

    System.out.println("Enter password"); 
    inputPassword = input.next(); 
    count++;  
} 
if ((inputUsername.equals(userName)) && (inputPassword.equals(password))) 
    System.out.println("You are now logged in"); 
else 
    System.out.println("You have enterede wrong three times. Please try again in a few hours"); 

    System.exit(0); 

再次感謝!

0

你的'休息'需要移動。

System.out.println("Enter password"); 
String inputPassword = input.next(); 

int count = 0; 

//create while loop, set loop continuation condition to count < 3 
while (count <= 2) {    

    if ((!inputUsername.equals(userName)) || (!inputPassword.equals(password))) {  
     System.out.println("Wrong entry. try again: Enter username"); 
     inputUsername = input.next(); 

     System.out.println("Enter password"); 
     inputPassword = input.next(); 
    } 
    else { 
     System.out.println("You are now logged in"); 
     break; 
    }    

    count++; 
} 

if (count > 2) 
    System.out.println("You have entered wrong three times. Please try again in a few hours"); 

System.exit(0);