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

为何这段输入缓冲区清空代码无法正常运行?

问题分析与解决方案

我来帮你搞定这个Scanner缓冲区的坑!你遇到的情况是Scanner常用方法的典型问题——nextInt()、nextDouble()这类方法只会读取对应类型的数值,完全不会处理输入末尾的换行符。当你输入完double按下回车后,缓冲区里会残留一个\n,这时候你调用scan.nextLine(),它会直接把这个空的换行内容赋值给s,而后面的scan.next()和scan.nextLine()根本不是在清空缓冲区,而是在等待你输入新内容,完全打乱了原本的输入逻辑。

修正后的代码

我们只需要调整缓冲区处理的时机,在读取完double之后,先调用一次nextLine()吃掉残留的换行符,再去读取字符串就可以了:

import java.util.Scanner;

public class Solution {
    // Java program for accepting an integer, a double and a string from the user.
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        
        int i = scan.nextInt();
        double d = scan.nextDouble();
        
        // 先吃掉nextDouble()留下的换行符
        scan.nextLine();
        // 现在可以读取完整的一行字符串了
        String s = scan.nextLine();
        
        // 打印输入内容
        System.out.println("String: " + s);
        System.out.println("Double: " + d);
        System.out.println("Int: " + i);
    }
}

补充说明

  • 如果你的字符串包含空格,scan.next()只能读取到第一个空格前的内容,所以用scan.nextLine()才能读取完整的一行输入。
  • 原代码的清空逻辑失效,核心原因是你把残留的空换行内容先赋值给了s,之后的scan.next()和scan.nextLine()属于额外的输入读取操作,完全偏离了你的预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 03:27:27