我正在寫一個隨機機會遊戲來挑選隨機贏家。我正在使用for循環將玩家輸入到數組中,但它不允許我爲第一個玩家輸入任何內容。下面是代碼:Java For Loop問題
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)]);
}
}
的想法!你創建一個基於'playernum'的字符串數組,因爲它的大小,然後嘗試循環通過增加的東西... – Tdorno
[nextXXX後使用nextLine時掃描程序問題]的可能重複(http://stackoverflow.com/問題/ 7056749/scanner-issue-when-using-nextline-after-nextxxx) – acdcjunior