Java如何自定义输入错误提示,替代InputMismatchException异常?
解决方案:自定义输入错误提示实现
要解决输入字符串时抛出默认异常、无法显示自定义提示的问题,你需要通过异常捕获处理非整数输入,同时保留数值合法性校验。以下是修改后的代码:
import java.util.InputMismatchException; import java.util.Scanner; class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int firstNum = 0; int secondNum = 0; boolean isValidInput = true; try { // 尝试读取两个整数 firstNum = scanner.nextInt(); secondNum = scanner.nextInt(); // 校验数值是否为正数(排除0和负数) if (firstNum <= 0 || secondNum <= 0) { isValidInput = false; } } catch (InputMismatchException e) { // 捕获输入非整数的异常 isValidInput = false; } if (!isValidInput) { System.out.println("Please enter a valid number!"); } else { // 执行加法操作 try { int add = Math.addExact(firstNum, secondNum); System.out.println(add); } catch (ArithmeticException e) { // 可选:处理加法溢出的情况,若不需要可移除该块 System.out.println("Number overflow!"); } } scanner.close(); } }
关键修改点说明:
- 异常捕获:用
try-catch包裹scanner.nextInt()调用,捕获输入非整数时触发的InputMismatchException,标记输入无效。 - 数值校验:读取到整数后,检查是否大于0,若为0或负数同样标记输入无效。
- 统一提示输出:根据
isValidInput状态,统一输出自定义错误提示或执行加法逻辑。
如果希望用户输入错误后可重新尝试,可添加循环逻辑:
import java.util.InputMismatchException; import java.util.Scanner; class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int firstNum = 0; int secondNum = 0; boolean isValidInput = false; while (!isValidInput) { try { System.out.print("输入第一个正整数:"); firstNum = scanner.nextInt(); System.out.print("输入第二个正整数:"); secondNum = scanner.nextInt(); if (firstNum > 0 && secondNum > 0) { isValidInput = true; } else { System.out.println("Please enter a valid number!"); } } catch (InputMismatchException e) { System.out.println("Please enter a valid number!"); scanner.next(); // 清除无效输入,避免死循环 } } // 执行加法 try { int add = Math.addExact(firstNum, secondNum); System.out.println("结果:" + add); } catch (ArithmeticException e) { System.out.println("Number overflow!"); } scanner.close(); } }
这个版本会持续提示用户重新输入,直到输入两个有效的正整数为止。
内容的提问来源于stack exchange,提问作者Shoxrux Atakov
相关产品推荐
相关产品推荐

