[英]Java Scanner exception handling
我想從用戶那里接收一個 Double 並處理在用戶沒有輸入 double/int 的情況下拋出的異常; 在這種情況下,我想請用戶再次插入金額。 如果異常被捕獲,我的代碼就會陷入循環,並繼續打印“插入數量”。
private static double inputAmount() {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Insert amount:");
try {
double amount = input.nextDouble();
return amount;
}catch (java.util.InputMismatchException e) {continue;}
}
}
先感謝您。
你的程序進入,當輸入無效,是因為遇到了一個無限循環nextDouble()
不消耗無效令牌。 因此,導致異常的任何標記都將保留在那里,並在您下次嘗試讀取 double 時繼續引發異常。
這可以通過在catch
塊中放置nextLine()
或next()
調用來解決,以消耗導致拋出異常的任何輸入,清除輸入流並允許用戶再次輸入某些內容。
原因是它一遍又一遍地讀取相同的值,因此每次都以 catch 子句結尾。
你可以試試這個:
private static double inputAmount() {
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Insert amount:");
try {
return input.nextDouble();
}
catch (java.util.InputMismatchException e) {
input.nextLine();
}
}
}
這是因為異常被捕獲后,它會留在掃描儀對象的緩沖區中。 因此它不斷拋出異常,但由於您使用 continue 處理它,它將在循環中運行。 嘗試調試程序以獲得更好的視圖。
此方法繼續執行相同的輸入標記,直到找到行分隔符,即input.nextLine()
或input.next()
查看以下代碼
private static double inputAmount()
{
Scanner input = new Scanner(System.in);
while (true)
{
System.out.println("Insert amount:");
try
{
double amount = input.nextDouble();
return amount;
}
catch (java.util.InputMismatchException e)
{
input.nextLine();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.