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

如何在while循环中使用Scanner扫描用户新输入,解决重复读取首条输入问题

问题根因
  • 循环读取输入异常是Scanner缓冲区换行符残留导致:如果你在循环后续的代码中使用了nextInt()这类非整行读取的方法,这类方法仅会读取对应类型的内容,不会消费输入末尾的换行符,下一次循环调用nextLine()时会直接读取到残留的换行符返回空串,看起来就像始终读取第一条输入。
  • scanner.next()默认以空白符作为分隔符,仅会读取到第一个空白符位置,必然丢失输入末尾的空白字符,不符合你的需求。
修复方案

保留nextLine()读取整行的逻辑,只需处理换行符残留问题即可,有两种常用修复方式:

方式1:非整行读取后主动消费残留换行

每次调用nextInt()这类非整行读取方法后,额外调用一次nextLine()消费残留的换行符:

inputText:
while(keepSorting){
    System.out.print("Please input the string to be sorted: " );
    // nextLine可完整读取整行,保留输入首尾所有空白字符
    c.settingInput(s.nextLine());
    System.out.println(" ");
    int option;

    // 原有读取选项的代码
    option = s.nextInt();
    // 新增:消费整数输入后残留的换行符
    s.nextLine();

    // more code
    .... 
}

方式2:全程使用nextLine读取再类型转换

所有输入都用nextLine()读取后,再自行转换为需要的类型,从根源避免换行符残留:

inputText:
while(keepSorting){
    System.out.print("Please input the string to be sorted: " );
    c.settingInput(s.nextLine());
    System.out.println(" ");
    int option;

    // 直接用nextLine读取整行后转成整数,不需要额外处理换行
    option = Integer.parseInt(s.nextLine());

    // more code
    .... 
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 17:27:01