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

Scanner在for循环中不等待输入的原因及修复方法

Scanner输入异常问题:为何玩家输入循环只获取一次输入?

问题原因

你遇到的问题是Scanner的输入缓冲区残留换行符导致的,具体逻辑是这样的:

  • 当你用userInput.nextInt()读取玩家数量时,它只会提取输入的数字部分,而你按下回车键确认输入时产生的**换行符(\n)**会留在输入缓冲区里。
  • 进入玩家输入循环后,第一个userInput.nextLine()会直接读取这个残留的换行符,相当于获取了一个空字符串,所以程序直接跳过了Player1的输入步骤,接着打印Player2:,这时候才会等待你输入内容——看起来就像是只获取了一次输入。
  • 而国家输入的循环能正常工作,是因为玩家循环的最后一个nextLine()已经把缓冲区里的剩余内容处理干净了,后续的nextLine()都会正常等待输入。

修复方案

这里有两种简单的修复方式,选一种即可:

方法1:消耗nextInt()残留的换行符

在读取完玩家数量后,额外调用一次nextLine()来清空缓冲区里的换行符:

out.println("How many players? ");
int limit = userInput.nextInt();
userInput.nextLine(); // 关键:消耗掉nextInt()留下的换行符

方法2:全程使用nextLine()读取输入

如果你不想处理缓冲区的问题,可以全程用nextLine()读取输入,再把玩家数量的字符串转换成整数:

out.println("How many players? ");
String inputStr = userInput.nextLine();
int limit = Integer.parseInt(inputStr);

修复后的完整代码示例

import java.util.Scanner;
import java.util.ArrayList; // 注意你原来的代码漏了这个导入,运行会报错
import java.lang.System.*;

public class countryRand {
    public static void main(String[] args) {
        Scanner userInput = new Scanner(System.in);
        out.println("How many players? ");
        int limit = userInput.nextInt();
        userInput.nextLine(); // 新增这一行处理换行符

        ArrayList<String> players = new ArrayList<String>();
        for (int index = 0; index < limit; index++) {
            out.println("Player" + (index + 1) + " : ");
            players.add(userInput.nextLine()); // 现在可以正常获取每个玩家的输入了
        }

        ArrayList<String> countries = new ArrayList<String>();
        for (int index = 0; index < limit; index++) {
            out.println("Country" + (index + 1) + " : ");
            countries.add(userInput.nextLine());
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 07:59:12