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

使用Java Scanner对象时如何捕获用户输入任意整数的异常

解决方案

核心修改点是替换原有的数字检测逻辑:

  • 原逻辑item.contains("1")仅能检测输入中是否包含字符1,无法覆盖其他数字场景
  • 你可以通过正则表达式快速实现任意数字的检测,两种常用匹配规则可按需选择:
    1. 只要输入包含任意数字就触发异常:使用正则.*\\d+.*
    2. 只有输入为纯整数(全部由数字组成)才触发异常:使用正则^\\d+$

修改后的完整代码

ExampleOne.java

import java.util.Scanner;

public class ExampleOne {
    // 原方法上的throws TestCustomException可删除,异常已在内部捕获无需外抛
    public static void main(String[] args) {
        System.out.println("Please enter any word:");
        try {
            Scanner scan = new Scanner(System.in);
            String item = scan.nextLine();
            // 这里用第一条规则,包含任意数字就抛异常,要换规则直接改matches里的正则即可
            if (item.matches(".*\\d+.*")) {
                throw new TestCustomException();
            }
        } catch (TestCustomException e) {
            System.out.println("A problem occured:  " + e);
        }
        System.out.println("Thank you for using my application.");
    }
}

TestCustomException.java (无需修改)

public class TestCustomException extends Exception {
    TestCustomException (){
        super("You can't enter any number value here");
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:27:01