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

使用Scanner读取数据时遭遇异常,寻求解决方案

解决Java Scanner混合输入(字符串+数字)的换行符问题

我太懂你遇到的这个问题了!这是Java新手用Scanner处理带空格的字符串和数字混合输入时,几乎都会踩的坑——明明调用了nextLine(),结果还是读不到想要的内容,甚至抛出异常。我来给你把问题拆透,再给你两种靠谱的解决方案。

问题根源

当你用nextInt()、nextDouble()这类方法读取数字时,Scanner只会读取数字本身,不会处理输入结束后你敲的那个换行符。这个换行符会留在输入缓冲区里,等你下一次调用nextLine()时,它会直接把这个空的换行符当成一行内容读走,而不是等待你输入新的内容。如果你的代码顺序不对(比如先读数字再读带空格的姓名),就会出现看起来“跳过输入”的情况,甚至因为类型不匹配抛出异常。

解决方案

方案1:读取数字后额外调用nextLine()消耗换行符

这是最直接的修复方式,在每次用nextInt()/nextDouble()之后,加一行sc.nextLine()把残留的换行符吃掉,这样后续的nextLine()就能正常读取你输入的内容了。

修正后的完整代码:

import java.util.Scanner;
import java.text.DecimalFormat;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // 用于把信用额度格式化为两位小数,匹配预期输出
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        
        System.out.print("输入客户姓名:");
        // 直接用nextLine读完整行,支持带空格的姓名
        String customerName = sc.nextLine();
        
        System.out.print("输入客户ID:");
        int customerId = sc.nextInt();
        // 关键:吃掉输入ID后留下的换行符
        sc.nextLine();
        
        System.out.print("输入信用额度:");
        double creditLimit = sc.nextDouble();
        
        // 格式化输出符合预期的结果
        System.out.println("客户详情为 客户姓名:" + customerName + ",客户ID:" + customerId + ",信用额度:" + decimalFormat.format(creditLimit));
        
        sc.close();
    }
}

方案2:统一用nextLine()读取所有输入,手动转换类型

这种方式更健壮,完全避免换行符的问题——不管是字符串还是数字,都用nextLine()读取整行内容,然后手动转换成对应的类型(比如Integer.parseInt()转整数,Double.parseDouble()转浮点数)。

完整代码示例:

import java.util.Scanner;
import java.text.DecimalFormat;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        
        System.out.print("输入客户姓名:");
        String customerName = sc.nextLine();
        
        System.out.print("输入客户ID:");
        // 读取整行后转成int类型
        int customerId = Integer.parseInt(sc.nextLine());
        
        System.out.print("输入信用额度:");
        // 读取整行后转成double类型
        double creditLimit = Double.parseDouble(sc.nextLine());
        
        System.out.println("客户详情为 客户姓名:" + customerName + ",客户ID:" + customerId + ",信用额度:" + decimalFormat.format(creditLimit));
        
        sc.close();
    }
}

为什么你之前的尝试没用?

如果你的代码是先读取数字(比如先读客户ID),再调用nextLine()读姓名,那这个nextLine()会先把数字后面的换行符读走,而不是等待你输入姓名。所以要么调整读取顺序(先读带空格的字符串,再读数字),要么在数字读取后加额外的nextLine()消耗换行符,两种方式都能解决问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:47:18