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

Java中Scanner调用nextInt后nextLine不等待输入是Bug吗?

问题解答

这不是Java的Bug,属于Scanner类的正常设计逻辑。

问题原因

  • nextInt()、nextFloat()等非nextLine()的输入读取方法,仅会提取输入流中对应类型的有效数据,不会处理用户输入完成后按下回车键产生的换行符\n,该换行符会一直残留在输入缓冲区中。
  • 后续执行nextLine()时,方法默认读取到换行符就判定为一行输入结束,因此会直接返回空内容,不会等待用户新的输入操作。

修复方案

方案1:消费残留换行符

在调用完nextInt()后额外执行一次无意义的nextLine(),清空缓冲区残留的换行符即可,对应代码修改如下:

import java.util.Scanner;
public class Strmethod {
    public static void main(String[] args)
    {
        String ch,fd;
        int s,e;
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter A String:");
        ch=sc.nextLine();
        System.out.println("String is "+ch);
        System.out.println("Enter Two Numbers For Substring:");
        s=sc.nextInt();
        e=sc.nextInt();
        // 新增此行,消费掉输入数字后残留的换行符
        sc.nextLine();
        System.out.println("Substring:"+ch.substring(s,e));
        System.out.println("Enter a Word to search:");
        fd=sc.nextLine();
        // 注意原代码此处变量名有误,应该是fd不是f
        System.out.println(ch.contains(fd));
        String jn=String.join("/","hello","g","u","y","s");
        System.out.println(jn);
        System.out.println(ch.startsWith("H"));
        System.out.println(ch.startsWith("e"));
        System.out.println("Length:"+ch.length());
        String newstr=ch.replace("Hello","Hey");
        System.out.println("String is "+ch);
            
    }
}

方案2:统一使用nextLine()读取输入

所有输入都通过nextLine()读取后,再手动转换为对应类型,从根源避免残留换行问题:

// 读取数字的示例
s = Integer.parseInt(sc.nextLine());
e = Integer.parseInt(sc.nextLine());

原输出附件

输出附件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 20:57:03