【问题标题】:Java not continuing a loop [closed]Java没有继续循环[关闭]
【发布时间】:2018-10-10 18:37:09
【问题描述】:

我正在制作一个简单的 for 循环来遍历 ArrayList 并向其中添加对象,但是当我输入我的第一个对象时没有任何反应。看起来程序没有继续循环。这是我所拥有的:

for (int i = 0; i < (numPlayers.nextInt()-1); i++){
    System.out.println("what is player " + (i + 1) + " name?");
    Scanner namePlayer = new Scanner(System.in);
    String playerName = namePlayer.nextLine();
    playerList.add(new Player(playerName));
}

播放器对象的构造函数也很简单

public Player(String name) {
    this.name = name
}

【问题讨论】:

  • 请提供minimal reproducible examplenumPlayers 是什么?
  • Scanner namePlayer = new Scanner(System.in); 移出for 循环
  • 无论numPlayers 是什么,看起来它在每次循环迭代时都会提供一个新值。你提供的第二个值是多少?如果该值小于 2,则循环将按照指示终止。
  • 每次调用 nextInt() 时都会读取一个新的 int。我假设您打算将 numPlayers.nextInt() 放入一个局部变量中,因此它只被调用一次。

标签: java arrays loops


【解决方案1】:
public static void main(String[] args)
    {
        Scanner numPlayers = new Scanner(System.in);
        ArrayList<Player> playerList = new ArrayList<>();
        int input = numPlayers.nextInt();

        for (int i = 0; i < input; i++){
            System.out.println("what is player " + (i + 1) + " name?");
            String playerName = numPlayers.next();
            playerList.add(new Player(playerName));
        }

    }

您应该在 for 循环之外声明 scanner 对象。您的代码的问题是每次在输入字符串后,您的代码都需要为(int i = 0; i &lt; (numPlayers.nextInt()-1); i++) 提供一个整数,这就是为什么如果您提供除整数之外的任何内容,它会给出InputMismatchException。所以你必须在 for 循环之外初始化输入常量,否则执行会动态变化。

【讨论】:

    【解决方案2】:

    如果可能,您只需定义一次循环的限制:

    int numberOfPlayers = numPlayers.nextInt()-1;
    for (int i = 0; i < numberOfPlayers; i++){
        System.out.println("what is player " + (i + 1) + " name?");
        Scanner namePlayer = new Scanner(System.in);
        String playerName = namePlayer.nextLine();
        playerList.add(new Player(playerName));
    }
    

    您需要确保您可以根据需要多次迭代循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 2011-08-19
      相关资源
      最近更新 更多