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