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

使用Scanner输入姓名时持续触发InputMismatchException的问题排查

Scanner触发InputMismatchException的问题分析

异常产生的核心原因

  • 调用sc.nextInt()读取人数后,输入缓冲区会残留用户按下的换行符(输入数字后回车产生)。
  • 进入循环后,第一个sc.nextLine()会直接读取这个残留的换行符,导致name被赋值为空字符串。
  • 后续执行sc.nextInt()时,程序期望读取整数类型的年龄,但此时用户输入的是姓名(字符串),类型不匹配,直接触发InputMismatchException。

修复方案

在读取人数的sc.nextInt()之后,添加一行sc.nextLine()清空缓冲区的换行符,修改后的代码如下:

Scanner sc = new Scanner(System.in);
System.out.println("How many People are there ? (employee and students included)");

int numPeople = sc.nextInt();
sc.nextLine(); // 清空numPeople输入后残留的换行符
Person[] personArray = new Person[numPeople];
Student[] studentsArray = new Student[numPeople];
Employee[] employeesArray = new Employee[numPeople];

int i = 0;

while(i < numPeople) {
    System.out.println("Please enter the name and age of the person");
    String name = sc.nextLine();
    int age = sc.nextInt();
    sc.nextLine(); // 保留此行,避免age输入后残留的换行符影响下一次循环
    Person person = new Person(name, age);
    personArray[i] = person;
    i++;
}

补充说明

  • nextInt()、next()这类方法仅读取输入中的有效数据,不会处理末尾的换行符;而nextLine()会读取从当前位置到换行符的所有内容,包括空内容。
  • 只要在nextInt()/next()之后需要调用nextLine(),都要手动处理残留的换行符,否则会出现读取内容不符合预期的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 01:07:34