[英]Exceptions handling
我希望它允許用戶在輸入錯誤之后輸入兩個int。 我試着繼續; 在catch塊中,但是它只會引發運行時錯誤。 我只希望它在引發錯誤后返回到main方法的頂部。 看看圖片中如何不允許用戶輸入任何數字。 我要修復該部分。
這是代碼。 這僅用於練習。
/**
practing exceptions, example 1 in book for exceptions
*/
import java.util.Scanner;
public class PracticeExceptions extends Exception {
public static void main(String[] args)
{
String response = "y";
Scanner keyboard = new Scanner(System.in);
do{
int n1, n2;
double r;
System.out.println("Please enter two numbers");
try{
n1 = keyboard.nextInt();
n2 = keyboard.nextInt();
r = (double) n1/n2;
System.out.format("Your answer: %.2f %n", r);
}catch(Exception a){
System.out.println("Invaild input please try again");
}
System.out.println("Again (y/n)");
response = keyboard.next();
}while(response.equalsIgnoreCase("y"));
}
}
擺脫掃描儀緩沖區中的無效輸入
}catch(Exception a){
System.out.println("Invalid input please try again");
keyboard.next();
}
該代碼現在將下拉至System.out.println("Again (y/n)");
如果要循環回到頂部,請在keyboard.next();
之后添加一個continue
keyboard.next();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.