我正在编写一个随机机会游戏来选择随机获胜者。我正在使用 for 循环将玩家输入到数组中,但它不允许我为第一个玩家输入任何内容。这是代码:
import java.util.Scanner;
import java.util.Random;
public class Run {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
Random rand = new Random();
System.out.println("How many people will play???");
int playernum = input.nextInt();
String players[] = new String[playernum];
for(int i = 0; i < playernum; i++){
System.out.println("Who is player #" + (i+1)+"?");
players[i] = input.nextLine();
}
System.out.println("The winner is: " + players[rand.nextInt(playernum)]);
}
}
最佳答案
input.nextInt()
调用读取整数,但在输入流中留下未读取的换行符,因此 input.nextLine()
调用在循环中只需在第一次迭代中读取该字符。
所以,您需要以下内容 -
int playernum = input.nextInt();
input.nextLine(); //read the unread new line character from the input stream
关于Java For 循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17416757/