使用Java Scanner对象时如何捕获用户输入任意整数的异常
解决方案
核心修改点是替换原有的数字检测逻辑:
- 原逻辑
item.contains("1")仅能检测输入中是否包含字符1,无法覆盖其他数字场景 - 你可以通过正则表达式快速实现任意数字的检测,两种常用匹配规则可按需选择:
- 只要输入包含任意数字就触发异常:使用正则
.*\\d+.* - 只有输入为纯整数(全部由数字组成)才触发异常:使用正则
^\\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
相关产品推荐
相关产品推荐

