在這個程式中,一旦例外被捕獲,程式就會顯示捕獲訊息并且程式會自行成功終止(如果想詢問用戶輸入,我需要再次手動運行程式)。我不希望程式完成,但它應該自動要求用戶輸入一個有效的數字并從頭開始執行功能,如何撰寫?
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Enter a Whole Number to divide: ");
int x = sc.nextInt();
System.out.println("Enter a Whole number to divide by: ");
int y = sc.nextInt();
int z = x / y;
System.out.println("Result is: " z);
}
catch (Exception e) {
System.out.println("Input a valid number");
}
finally{
sc.close();
}
}
}
輸出
Enter a Whole Number to divide:
5
Enter a Whole number to divide by:
a
Input a valid number
Process finished with exit code 0
uj5u.com熱心網友回復:
有一些nextInt您需要注意的問題,您可以查看此鏈接:Scanner is skipping nextLine() after using next() or nextFoo()? .
對于您的程式,請使用 while 回圈,并且您需要注意 Y 可能為 0,這會導致ArithmeticException.
while (true) {
try {
System.out.println("Enter a Whole Number to divide: ");
// use nextLine instead of nextInt
int x = Integer.parseInt(sc.nextLine());
System.out.println("Enter a Whole number to divide by: ");
int y = Integer.parseInt(sc.nextLine());
if (y == 0) {
System.out.println("divisor can not be 0");
continue;
}
double z = ((double) x) / y
System.out.println("Result is: " z);
break;
}
catch (Exception e) {
System.out.println("Input a valid number");
}
}
sc.close();
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/362756.html
上一篇:PIL的問題
