首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java 控制台輸入區間驗證:do-while 循環守衛合法數值

     編輯:程式設計綜合問答

標準模式

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;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved