You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java如何判定用户输入数字而非字符串的异常,解决do-while循环重复报错问题

do-while循环重复报错问题

问题根因

  1. town变量的赋值放在了循环外部,循环内调用scanner.nextLine()读取新输入时,没有将新输入赋值给town,每次校验用的都是第一次输入的错误值,所以一直触发无效提示。
  2. 缺少空输入校验,用户直接回车的话调用charAt(0)会抛出字符串索引越界异常。

修复代码

boolean tryAgain;
String town;
do {
    tryAgain = false;
    System.out.println("请输入城市名:");
    town = scanner.nextLine();
    // 先判空,再校验是否包含数字
    if (town.isBlank() || town.matches(".*\\d.*")) {
        System.out.println("You probably entered an invalid data format");
        tryAgain = true;
    }
} while (tryAgain);

如果仅需要校验首字符不能为数字,把正则判断替换为Character.isDigit(town.charAt(0))即可。


try-catch无法捕获InputMismatchException问题

问题根因

Scanner.nextLine()会将任何输入内容都作为字符串返回,输入数字本质上也是字符串类型的"123",和方法的返回类型匹配,不会触发InputMismatchException。该异常仅在调用nextInt()、nextDouble()等特定类型读取方法,输入内容和目标类型不匹配时才会抛出。

适配校验方案

如果要走异常捕获的逻辑,可以通过尝试转换数字的方式触发异常,实现校验:

String town;
while (true) {
    System.out.println("enter the name of the city");
    town = scanner.nextLine();
    if (town.isBlank()) {
        System.out.println("You probably entered an invalid data format");
        continue;
    }
    try {
        // 尝试将输入转为数字,转换成功说明输入全为数字,格式非法
        Integer.parseInt(town);
        System.out.println("You probably entered an invalid data format");
    } catch (NumberFormatException e) {
        // 转换失败说明输入包含非数字内容,符合要求,跳出循环
        break;
    }
}

内容的提问来源于stack exchange,提问作者Vs_De_S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 10:15:04