Java求助:如何获取用户输入的错误数据类型(非int)?
问题修复:错误提示显示正确的输入类型
问题原因
你当前代码的核心问题是:catch块中调用((Object) age).getClass().getSimpleName()时,age本身是int类型——无论输入是否成功,它的装箱类型永远是Integer,哪怕输入失败,age也只是保留初始值0,完全和用户实际输入的内容无关,所以错误提示永远显示Integer。
修复方案
方案1:先读取为字符串再转换(推荐)
这种方式直接获取用户的完整输入,能准确判断输入类型,同时避免Scanner缓冲区的潜在问题:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("What is your age?"); // 先读取整行输入为字符串 String input = sc.nextLine(); try { // 尝试将字符串转为整数 int age = Integer.parseInt(input); if (age >= 18) { System.out.println("You are an adult."); } else { System.out.println("You are not an adult."); } } catch (NumberFormatException e) { // 转换失败时,直接获取输入内容的类型 System.out.println("Error: you did not input a full number, instead you wrote a " + input.getClass().getSimpleName()); } } }
方案2:在原代码基础上读取无效输入
如果你想保留nextInt()的写法,需要在catch块中读取Scanner缓冲区里未被处理的无效输入,再获取它的类型:
import java.util.Scanner; import java.util.InputMismatchException; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("What is your age?"); int age = 0; try { age = sc.nextInt(); if (age >= 18) { System.out.println("You are an adult."); } else { System.out.println("You are not an adult."); } } catch (InputMismatchException e) { // 读取缓冲区中的无效输入内容 String invalidInput = sc.next(); System.out.println("Error: you did not input a full number, instead you wrote a " + invalidInput.getClass().getSimpleName()); } } }
额外注意事项
- 尽量捕获具体异常(比如
InputMismatchException或NumberFormatException),而不是通用的Exception,这样能避免捕获到无关异常,代码更严谨。 - 方案1中的
nextLine()会读取用户输入的整行内容,包括空格,比方案2的next()更适合处理用户的自由输入场景。
内容的提问来源于stack exchange,提问作者fedyafrench
相关产品推荐
相关产品推荐

