0

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());
    }
}
Cho Dien
  • 5
  • 3
  • 1
    You need extra `nextLine` after you read in number of players with `nextInt`, since there is a trailing new line after the number. – nhahtdh Jul 23 '12 at 12:03
  • See my [previous answer to a different take of this problem](http://stackoverflow.com/a/11541456/1343161). – Keppil Jul 23 '12 at 12:11

3 Answers3

0

This should work

private int numPlay(){
        System.out.print("Enter how many players: ");
        return Integer.parseInt(keyboard.nextLine());
    }
Algorithmist
  • 6,657
  • 7
  • 35
  • 49
  • This comes with assumption that there is no leading/trailing spaces. It's a bit stricter than nextInt(), then a nextLine(). – nhahtdh Jul 23 '12 at 12:08
0

If the name is composed of one word than you can call the keyboard.next() function and not the keyboard.nextLine() function at String name = keyboard.nextLine();

M. Abbas
  • 6,409
  • 4
  • 33
  • 46
0

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'.

jcklie
  • 4,054
  • 3
  • 24
  • 42