在構建一個程序,其中用戶輸入3到10之間的高度,並且使用java打印來自zelda的triforce。在當前時刻,只要用戶輸入該範圍以外的數字,就會拋出異常,但是我希望程序在任何字符串輸入時都拋出異常。我不知道如何利用InputMismatchException
。這是到目前爲止我的代碼:異常沒有被執行
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int height;
try {
System.out.print("Enter height: ");
height = keyboard.nextInt();
}
catch (InputMismatchException e) {
System.out.println("");
System.out.println("Invalid height.");
}
if (height < 3 || height > 10) {
System.out.println("Invalid height.");
System.exit(0);
}
你問一個'int',如果你想檢查一個字符串已經輸入,然後在'掃描儀#next'或'掃描器讀取# nextLine'並在try-catch塊中使用'Integer#parseInt'。 –
您不應該在「錯誤」條件下使用'System.exit(0)':按照慣例,以零錯誤代碼退出意味着「成功」。而且,你應該在代碼中很少使用'System.exit':'return'在這裏會有相同的效果。 –