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

为什么使用Scanner读取整数、浮点数后要调用sc.nextLine()才能读取字符串?

Java Scanner类nextInt/nextDouble后调用nextLine读取失败原因说明

根本原因

Scanner的nextInt()、nextDouble()这类非整行读取的API,只会读取输入流中对应数据类型的有效内容,不会消费掉用户输入完成后按下回车产生的\n换行符。这个残留的换行符会留在输入缓冲区中,后续第一次调用nextLine()的时候,会直接读取到这个空的换行内容,就会出现“捕获不到输入内容”的现象。

示例代码处理逻辑说明

你给出的代码中nextDouble()之后额外调用的sc.nextLine()就是用来消费掉缓冲区里残留的换行符的,这样后续的nextLine()就能正常读取到用户输入的完整字符串内容,处理逻辑是完全正确的。

完整可运行代码

import java.util.Scanner;
public class Solution {

    public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            System.out.println("Please enter integer, double and string");  
            int x=sc.nextInt();
            double y=sc.nextDouble();
            // 消费缓冲区残留的换行符,避免后续nextLine读取到空内容
            sc.nextLine();
            String s=sc.nextLine();

            System.out.println("String: "+s);
            System.out.println("Double: "+y);
            System.out.println("Int: "+x);
    }
}

其他可选处理方案

如果不想多写一行消费换行的代码,也可以统一用nextLine()读取所有输入,再自行转换为对应类型:

  • 读取整数:int x = Integer.parseInt(sc.nextLine())
  • 读取浮点数:double y = Double.parseDouble(sc.nextLine())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 05:36:02