我已經看過類似的問題,並試圖解決其他人遇到的問題,但把sc.next()或sc.nextLine )在while循環之後導致它進入無限循環。Java掃描儀在數據類型驗證錯誤輸入後沒有讀取newLine while循環
問題是,如果用戶在輸入正確的信息前多次輸入錯誤的輸入(無數或數字),我會得到空行。正如我的輸出塊所示,當我輸入1作爲名字時,我必須輸入它兩次,才能輸出它是錯誤的格式,然後輸入空行,直到我輸入另一個字符。
我知道它與nextInt()沒有閱讀換行符有關,但是如何讓它在此方法中正確工作?
protected static void setFirstName(){
System.out.print("First Name: ");
while(sc.nextLine() == "" || sc.nextLine().isEmpty()){
System.out.println("Name is empty. Please Try again.\nFirst name:");
sc.nextLine();
}
while (sc.hasNextInt() || sc.hasNextDouble()) {
System.out.print("Incorrect Name format. Please Try again.\nFirst name: ");
sc.nextLine();
}
firstName = sc.nextLine();
firstName = Character.toUpperCase(firstName.charAt(0)) + firstName.substring(1);
}
這裏的輸出我得到當我第一次輸入一個號碼,然後空白的回報:
First Name: 1
1
Incorrect Name format. Please Try again.
First name:
1
Incorrect Name format. Please Try again.
First name: Incorrect Name format. Please Try again.
First name: Incorrect Name format. Please Try again.
First name: Incorrect Name format. Please Try again.
First name: Incorrect Name format. Please Try again.
First name:
這裏的輸出我得到當我第一次進入一個空白的回報,然後一個數字:
First Name:
Name is empty. Please Try again.
First name:
1
1
1
1
Incorrect Name format. Please Try again.
First name:
你的問題不清楚究竟發生了什麼問題。但是,將調用與'sc.next()'(通常不會從輸入行的末尾拉動換行符)和'sc.nextLine()'調用是非常糟糕的主意, 。嘗試將你的三個調用改爲'sc.next()'到'sc.nextLine()'。 –
謝謝,我按照你的建議完成了。 –