我是java的新手,很难为一个简单的游戏将玩家(1-4之间(添加到数组列表中。我的想法是,程序通过询问用户(来自同一台计算机,非常基本(将播放多少来打开,并通过输入名称来继续。完成后,将显示主菜单。我把下面的内容重写了好几个小时,就是想不通。我意识到playerTurn可能在这段代码中没有位置,但我觉得我已经尝试过了我能想到的一切。请帮忙!
Scanner input = new Scanner(System.in);
public int rounds; // 5-30
public int playerTurn; // to choose how many will be playing. 1-4
public ArrayList<Player> players = new ArrayList<>();
public Game() {
System.out.println("Welcome to The Farm! Please enter how many will be playing today (1-4 players) by entering your names. When finished please enter menu to begin");
String names = input.next();
while (true) {
for (int playerTurn = 0; playerTurn < 4; playerTurn++) {
newPlayer(names); // calls add player method
}
}
}
public void newPlayer(String newPlayer) {
players.add(new Player(newPlayer));
}
你看起来很困惑。
首先,你需要了解有多少球员将参加比赛。您这样做了,但出于某种原因,您将其分配给names
,然后用它创建一个Player
,这是没有意义的。然后你必须根据数字进行循环,在每次迭代时,你都会要求一个名字并创建一个玩家。
public static void main() {
int numOfPlayers = getNumOfPlayers();
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter the number of players");
int numOfPlayers = reader.nextInt();
if (numOfPlayers > 4) // display error message - exit
for (int i = 0; i < numOfPlayers; ++i) {
String playerName = reader.nextLine();
players.add(new Player(playerName));
}
reader.close();
}
您的类构造函数有一个无限循环(while(true)
(,因此它只是不断添加Player
实例,直到您终止程序。
public class Game {
private Scanner input = new Scanner(System.in); // Scanner reading from System.in
private int rounds; // 5-30
private int playerAmount; // Indicating how many players take part
private ArrayList<Player> players = new ArrayList<>(); // Storing player instances
public Game() {
System.out.println("Welcome to The Farm! Please enter how many will be playing today (1-4 players) by entering your names. When finished please enter menu to begin");
for(int i = 0; i < 4; i++) {
String name = input.readLine();
if (name.equals("menu") || players.size() >= 4) {
break; // User entered menu or the there are already 4 players in the ArrayList -> break out of the for loop
}
newPlayer(name); // New player gets added if the if-condition above isn't executed
}
playerAmount = players.size();
}
}
这样,当您实例化Game类时,将提示用户输入玩家名称,for循环将只执行4次,除非输入等于"menu"
或达到最大玩家数量。最后,ArrayList的大小决定了输入了多少名字,从而决定了有多少玩家在玩。