I haven't been programming for long and I have spent hours trying to get this method to do what I need so help would be very much appreciated at this point. I am creating a board game which prompts players for the number of players playing, after which they are prompted for their names in turn, and those new players will be created and their names set/stored. I also want to make sure that two players cannot have the same name.
Here is part of my player class:
public class Player {
private String name;
private int currentPosition;
private int distance;
private boolean quit;
public Player() {
}
public Player(String name, int currentPosition, int distance, boolean quit) {
this.name = name;
this.currentPosition = currentPosition;
this.distance = distance;
this.quit = quit;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I have a setNumberOfPlayers method which is working fine and getting the correct number of players when getNumberOfPlayers() is called.
public class SetUpGame {
Scanner sc = new Scanner(System.in);
public void addPlayers() {
String playerName;
ArrayList<Player> players = new ArrayList<Player>();
System.out.println("What are the names of the " + this.numberOfPlayers + " players?\n");
for (int loop = 1; loop <= getNumberOfPlayers(); loop++) {
System.out.println("Player " + loop + " please enter your name");
boolean valid = false;
do {
playerName = sc.nextLine();
Player player = new Player();
for (Player play : players) {
if (players.isEmpty() || !play.getName().equalsIgnoreCase(playerName)) {
player.setName(playerName);
players.add(player);
System.out.println("success, your name is: " +playerName);
valid = true;
} else {
System.out.println("please enter another name");
valid = false;
}
}
} while (valid == false);
}
sc.close();
}
When the add players method is called from main, it gives this output:
What are the names of the 2 players?
Player 1 please enter your name
...and the user can input their name but the scanner never closes or loops around to ask the next player their name. I have messed around with the code so much that I've confused myself at this point. Can anyone help with this, and also how to validate/check that the players have been created and their names set? Thank you