程序要求用戶輸入雙數字1和雙數字2 ,如果有例外,我希望它再次詢問數字1和數字2的輸入嘗試在do while while循環中捕獲
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
double num1, num2;
int error = 0;
int text;
System.out.print("Enter 4 ");
text = sc.nextInt();
do{
try{
if(text == 4){
System.out.print("Enter number 1: ");
num1 = sc.nextDouble();
System.out.print("Enter number 2: ");
num2 = sc.nextDouble();
double quotient = num1/num2;
System.out.println("The Quotient of "+num1 + "/" +num2+ " = "+quotient);
}
}catch(Exception ex){
System.out.println("You've entered wrong input");
error = 1;
}
}while(error == 1);
}
然後當我嘗試代碼,如果它會通過在NUM1或num輸入查詢字符串捕獲異常2我在這個無限循環: Enter number 1: You've entered wrong input Enter number 1: You've entered wrong input Enter number 1: You've entered wrong input Enter number 1: You've entered wrong input Enter number 1: You've entered wrong input
請提供[mcve](注意「完整」位)。 – assylias
你從哪裏獲得雙倍? – Shirkam
通過聲明和(重新)使用從用戶獲取輸入的單獨方法,直到用戶輸入有效數據爲止,您的代碼將受益。 – Bohemian