Java简易计算器:实现非数字输入的错误提示功能
解决Java计算器输入非数字报错的问题
你的问题出在Scanner.nextInt()方法上——当用户输入非整数内容时,这个方法会直接抛出InputMismatchException,导致程序崩溃。下面我给你一套友好的修复方案,既能在输入错误时给出指定提示,还能让用户重新输入合法内容,同时优化了代码的可读性和健壮性:
修改后的完整代码
import java.util.InputMismatchException; import java.util.Scanner; public class Calculator { public static void main(String[] args) { Scanner test = new Scanner(System.in); // 调用封装好的方法获取合法整数 int x = getValidInteger(test, "Insert a number "); System.out.println("Insert a value e.g * / + -"); String c = test.next(); int y = getValidInteger(test, "Insert another number "); // 用switch替代多个if,逻辑更清晰 switch (c) { case "*": System.out.println("the total is " + x * y); break; case "+": System.out.println("the total is " + (x + y)); break; case "-": System.out.println("the total is " + (x - y)); break; case "/": // 额外处理除数为0的情况 if (y == 0) { System.out.println("Cannot divide by zero!"); } else { System.out.println("the total is " + (x / y)); } break; default: System.out.println("Invalid operator! Please use *, /, +, or -"); } test.close(); } // 封装获取合法整数的逻辑,避免重复代码 private static int getValidInteger(Scanner scanner, String prompt) { int number = 0; boolean isInputValid = false; while (!isInputValid) { System.out.print(prompt); try { number = scanner.nextInt(); isInputValid = true; } catch (InputMismatchException e) { // 输入非法时给出提示 System.out.println("please enter a number"); // 清除输入缓冲区的无效内容,防止死循环 scanner.next(); } } return number; } }
核心改进说明
- 异常捕获与提示:用
try-catch块捕获InputMismatchException,在用户输入非数字时打印你需要的提示信息,同时通过scanner.next()清空缓冲区的无效内容,避免程序陷入死循环。 - 代码复用:把获取合法整数的逻辑封装成
getValidInteger方法,减少重复代码,让主方法更简洁。 - 可读性优化:用
switch语句替代多个独立if,运算符判断逻辑更清晰;同时修正了类名(Calculator符合Java大驼峰命名规范)。 - 额外健壮性处理:增加了除法时除数为0的判断,避免出现另一种崩溃场景。
这样修改后,用户输入"abc"这类非数字内容时,程序会立刻提示"please enter a number",并等待用户重新输入合法数字,不会直接崩溃。
内容的提问来源于stack exchange,提问作者Ovidiu Vacaru
相关产品推荐
相关产品推荐

