[英]Java try catch issue
我要用此代碼完成的所有工作是檢查用戶的輸入是否為整數,然后給他們3次機會,如果輸入的數據類型不正確,請再次輸入。 如果它們達到“ maxTries”標記,然后最終引發異常。
任何幫助將不勝感激。 干杯。
boolean correctInput = false;
int returnedInt = 0;
int count = 0;
int maxTries = 3;
Scanner kybd = new Scanner(System.in);
while(!correctInput)
{
try
{
System.out.println("\nInput your int, you have had:" + count + " tries");
returnedInt = kybd.nextInt();
correctInput = true;
}
catch(InputMismatchException e)
{
System.out.println("That is not an integer, please try again..");
if (++count == maxTries) throw e;
}
}
return returnedInt;
發生這種情況的原因是未清除掃描儀的緩沖區。 輸入kybd.nextInt()
已經填充了一個非整數,但是由於讀取失敗,因此實際上並沒有擺脫它。 因此,第二個循環將嘗試再次拉出已經錯誤的填充緩沖區。
要解決此問題,您可以在異常處理中使用nextLine()
清除緩沖區。
} catch (InputMismatchException e) {
System.out
.println("That is not an integer, please try again..");
kybd.nextLine(); //clear the buffer, you can System.out.println this to see that the stuff you typed is still there
if (++count == maxTries)
throw e;
}
另一種選擇是使用String s = kybd.nextLine()
並解析為Integer並從中捕獲異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.