java - for循环跳过问题

标签 java arrays for-loop skip

我有这段代码,一切都按照我想要的方式运行,除了第一次应该等待用户下一次输入时跳过的面孔。这是代码:

import java.util.Scanner;
public class mainThread {
    public static int size;
    public static int counter;
    public static Scanner input = new Scanner(System.in);
    public static String currentIn;
    public static void main(String[] args){
        System.out.println("Please type the desired amount of players: ");
        size = input.nextInt();
        String nameArray[] = new String[size];
        for(int counter = 0; counter < size; counter++){
            System.out.println("Please enter the name of player " + (counter+1));
            currentIn = input.nextLine();
            nameArray[counter] = currentIn;
            System.out.println(nameArray[counter]);
        }
    }
}

控制台的内容如下:

Please type the desired amount of players: 
3
Please enter the name of player 1

Please enter the name of player 2
Jacob
Jacob
Please enter the name of player 3

它完全跳过了第一个循环,我似乎不明白为什么。感谢您的宝贵时间!

最佳答案

nextInt() 仅读取“3”,而不读取换行符部分。它基本上只是读取第一个 token 分隔符,但不消耗它。因此,如果您输入

3 Foo

然后然后按回车键,它将采用“Foo”作为第一个玩家的名字。

听起来您可能也想在查找玩家数量时使用nextLine():

String playerCountText = input.readLine();
size = Integer.parseInt(playerCountText); // Or use a NumberFormat

就我个人而言,我一直觉得 Scanner 像这样有点烦人 - 它似乎 promise 让一切变得简单,但你确实需要弄清楚它要做的一切...

关于java - for循环跳过问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15596594/

相关文章:

python - 在 python 中创建成对元素列表

javascript - 当从 `for` 循环内的 while 循环将值插入数组时,它会覆盖数组中的先前元素

java - 在java中编辑二进制文件

arrays - 在c中反转图像强度

arrays - 计算列表或 3D 数组中矩阵的总和

Java 数组拆分和重新连接。丢失的元素

带有 Laravel Blade 模板循环和总和的 JavaScript

java - 如何确定java Web应用程序中资源的路径

java - 如何有效地进行多线程

java - Java 对象引用是如何工作的?