標準模式
Scanner sc = new Scanner(System.in);
int min = 10, max = 100;
int value;
do {
System.out.printf("請輸入 [%d, %d] 間的整數:", min, max);
while (!sc.hasNextInt()) {
System.out.println("非整數,重新輸入:");
sc.next(); // 丟棄無效 token
}
value = sc.nextInt();
} while (value < min || value > max);
System.out.println("輸入合法:" + value);
關鍵點
do-while 保證至少執行一次。
sc.hasNextInt() 預檢 token 類型,避免 InputMismatchException。
- 非法 token 必須
sc.next() 消費掉,否則死循環。
函數式封裝
public static int readIntInRange(Scanner sc, String prompt, int min, int max) {
int v;
do {
System.out.print(prompt);
while (!sc.hasNextInt()) { System.out.println("請輸入整數!"); sc.next(); }
v = sc.nextInt();
} while (v < min || v > max);
return v;
}