I’m writing a card game. I’ve encountered a problem and can’t seem to figure it out. I’m trying to add players to an array by firstly having the user specify the array size. Then ask user to enter the name of players to add to the array. I have a problem with the loop, during the first loop “Enter name: ” will be print 2 times before the user can have input. Can somebody help me with this. Thank you.
public class Dealer {
Scanner keyboard = new Scanner(System.in);
private Deck deck = new Deck();
Player[] players;
public static void main(String []args){
new Dealer();
}
public Dealer(){
addPlayers();
print();
}
private void addPlayers(){
int num = numPlay();
players = new Player[num];
for(int i=0; i<num; i++){
System.out.println("Enter name: ");
String name = keyboard.nextLine();
players[i] = new Player(name);
}
}
private int numPlay(){
System.out.print("Enter how many players: ");
return keyboard.nextInt();
}
private void print(){
for(Player x: players)
System.out.println(x.toString());
}
}
As stated already, if you call
numPlay(), the Scanner reads the number AND the line ending character which is given by the pressing of the Enter key. Since you used nextInt(), the newline remains in the scanner.Therefore, some string is remaining in the buffer and the next call to read from the scanner simply returns this new line; it does not wait for your input.
In addition, it seems as if it creates an player with a name of ‘\n’.