我希望用戶輸入80到120之間的整數,沒有字母和其他符號。這裏是我的代碼:如何檢查用戶是否輸入2個數字之間的整數?
import java.util.*;
public class Test {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
//checking for integer input
while (!in.hasNextInt())
{
System.out.println("Please enter integers between 80 and 120.");
in.nextInt();
int userInput = in.nextInt();
//checking if it's within desired range
while (userInput<80 || userInput>120)
{
System.out.println("Please enter integers between 80 and 120.");
in.nextInt();
}
}
}
}
不過,我面臨的一個錯誤。有針對這個的解決方法嗎?
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Array.main(Array.java:15)
謝謝! :)
編輯:謝謝湯姆,得到了解決,但想嘗試沒有「做」
Scanner in = new Scanner(System.in);
int userInput;
do {
System.out.println("Please enter integers between 80 and 120.");
while (!in.hasNextInt())
{
System.out.println("That's not an integer!");
in.next();
}
userInput = in.nextInt();
} while (userInput<81 || userInput >121);
System.out.println("Thank you, you have entered: " + userInput);
}
}
當然有!抓住java.util.InputMismatchException並適當處理它。出於興趣,你爲什麼要跳過輸入? – Bathsheba
@Bathsheba你好,我想這樣做沒有使用捕捉,因爲我正在修改我的學校工作,這只是前幾個主題(在這一點上沒有學到異常) – Ken
將條件改爲while (in.hasNextInt()) – Unknown