You need to enable JavaScript to run this app. Java中Scanner的next()不支持空格、nextLine()跳过输入问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

Java中Scanner的next()不支持空格、nextLine()跳过输入问题咨询

问题根因拆解
  • next()方法的读取规则:仅读取从当前光标位置到第一个出现的空白字符之间的内容,遇到空格、换行就停止截取,因此输入带空格的"Root Beer"时,只会拿到前半段的"Root"。
  • nextLine()方法的异常表现根源:该方法的读取规则是一直读到当前行末尾的换行符才返回完整内容。如果之前调用过next()、nextInt()这类非整行读取的Scanner方法,这些方法不会消费用户输入后留下的换行残留,nextLine()被调用时会直接读到残留的换行符,判定一行读取完成,根本不会等待用户输入,表现为直接跳过输入环节。

其他场景下nextLine()能正常工作,本质是代码中没有混用其他非整行读取的Scanner方法,不存在输入流残留的问题,并非方法本身功能有缺陷。

调整方案

统一使用整行读取的方式获取输入,从根源上避免读取规则不匹配和流残留的问题,调整后的可运行代码如下:

// 保持原有Scanner初始化逻辑不变
Scanner keyboard = new Scanner(System.in);
while(true) {
    System.out.println("Please enter a brand of soda. ");
    System.out.print("You can choose from Pepsi, Coke, Dr. Pepper, or Root Beer: ");
    // 读取完整整行输入,trim()去掉用户输入时误带的首尾空格
    String sodaType = keyboard.nextLine().trim();
    System.out.println("sodatype" + sodaType);
    if (sodaType.equalsIgnoreCase("pepsi") || sodaType.equalsIgnoreCase("coke") || 
            sodaType.equalsIgnoreCase("dr pepper") || sodaType.equalsIgnoreCase("dr. pepper") || 
            sodaType.equalsIgnoreCase("root beer")) 
    {
        System.out.println("you chose " +  sodaType);
        break;
    }
    else {
        System.out.println("Please enter an available brand of soda. ");
    }
}

补充提示:如果这段循环逻辑之前,你的代码里有用过keyboard.nextInt()、keyboard.next()这类非整行读取的方法,必须在第一次调用nextLine()之前,单独执行一次keyboard.nextLine()把输入缓冲区里残留的换行符消费掉,才能避免跳过输入的问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.20 06:45:05