
java 不支持直接用 `` 比较字符串数值大小;必须先将字符串安全转换为整数,再进行范围校验,并通过 try-catch 处理非法输入(如字母),避免 numberformatexception 崩溃程序。
在 Java 中,字符串(String)是引用类型,其比较操作符 根本无法编译通过——这与 JavaScript 等动态语言不同。即使 "100" > "18" 在字典序(lexicographic order)下为 false(因为 '1' == '1',但 '0' 数值意义上的范围判断(即 1 ≤ 输入 ≤ 180),而非字符串首字符 ASCII 大小。
因此,正确的做法是:将用户输入的字符串显式解析为整数,并在解析失败或超出范围时给出友好提示。关键在于两点:
✅ 使用 Integer.parseInt() 进行类型转换;
✅ 用 try-catch 捕获 NumberFormatException,处理非数字输入(如 "d"、""、"12.5" 等)。
以下是一个健壮、可复用的输入验证方法示例:
import java.util.Scanner;
public class InputValidator {
private static Scanner scanner = new Scanner(System.in);
public static int lireNombreDansPlage(int min, int max) {
while (true) {
System.out.printf("Entrez un nombre entier entre %d et %d (inclus) : ", min, max);
String input = scanner.nextLine().trim(); // 去除首尾空格,避免空输入误判
try {
int value = Integer.parseInt(input);
if (value >= min && value <= max) {
return value;
} else {
System.out.printf("Erreur : %d n'est pas dans la plage [%d, %d].\n", value, min, max);
}
} catch (NumberFormatException e) {
System.out.println("Erreur : l'entrée n'est pas un nombre entier valide.");
}
}
}
// 使用示例
public static void main(String[] args) {
int nbJoursLouer = lireNombreDansPlage(1, 180); // 注意:题目要求“> 0 且 ≤ 180”,即 [1, 180]
System.out.println("Nombre de jours valide saisi : " + nbJoursLouer);
}
}⚠️ 注意事项:
- 不要尝试用字符串比较替代数值比较(如 nbJoursLouer
- Clavier.lireString() 是自定义工具类方法,实际项目中建议统一使用 Scanner.nextLine() 并做好 trim();
- 条件判断中应使用 >= 1 && 0 ||
- 若需支持更大范围或非 int 类型(如 long),可替换为 Long.parseLong() 并调整异常类型。
总结:面向用户输入的数值校验,本质是「解析 → 验证 → 反馈」三步闭环。放弃字符串比较幻想,拥抱显式类型转换与异常处理,才能写出健壮、可维护的交互逻辑。
立即学习“Java免费学习笔记(深入)”;









