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

两段Java Scanner代码差异解析:为何其中一段抛出InputMismatchException异常

问题解析:Scanner的next()与nextInt()导致的InputMismatchException

嗨,作为Java新手遇到这个问题很正常,我来帮你把这个逻辑理清楚~

第一段代码抛出异常的核心原因

你第一段代码里的问题出在sc.next()和sc.nextInt()的配合上:

  • sc.next()的特性是只读取到第一个空白字符(空格、换行、制表符)之前的内容。当你输入Peter Henrik 22时,sc.next()只会截取到第一个空格前的Peter,此时输入缓冲区里还剩下 Henrik 22(注意开头的空格)。
  • 接下来调用sc.nextInt()时,它会自动跳过前面的空白,然后尝试读取剩下内容的第一个部分——也就是Henrik,这显然不是整数类型,所以JVM直接抛出InputMismatchException。

第二段代码为什么正常运行

第二段代码没有尝试用next()去读取全名,而是直接把之前通过sc.nextLine()获取的firstName和lastName拼接成完整姓名,最后用sc.nextInt()读取单独输入的22——这是合法的整数,自然不会触发异常。

如何修复第一段代码的问题

如果你想实现「一次性输入全名+年龄」的需求,推荐用整行读取后拆分的方式,这样能兼容全名包含多个空格的情况,示例代码如下:

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String firstName, lastName, completeName;
        int age;

        System.out.println("Please enter your first name: ");
        firstName = sc.nextLine();
        System.out.println("Please enter your last name: ");
        lastName = sc.nextLine();

        System.out.println("Please enter your complete name and your age: ");
        // 读取整行输入
        String fullInput = sc.nextLine();
        // 拆分输入内容,按空格分割
        String[] inputParts = fullInput.split(" ");
        // 最后一个元素是年龄,转成int类型
        age = Integer.parseInt(inputParts[inputParts.length - 1]);
        // 拼接前面所有元素作为完整姓名
        completeName = String.join(" ", Arrays.copyOfRange(inputParts, 0, inputParts.length - 1));

        System.out.println("Your complete name is: " + completeName);
        System.out.println("Your age is: " + age);
    }
}

补充:Scanner常用读取方法的区别

为了避免以后再踩类似的坑,记住这几个核心方法的差异:

  • next():读取到第一个空白字符为止,返回字符串,不消耗空白字符本身。
  • nextLine():读取到换行符为止,返回整行内容(不含换行符),会消耗换行符。
  • nextInt():跳过前面的空白字符,读取连续的数字部分,只能处理整数输入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 12:42:49