Xiris
Xiris

Reputation: 15

Using multiple scanners failed - Java

I have a problem with Scanner class. I have a few methods which read certain input from the user, however after invoking first method others crash (cannot read input). I searched for the solution and it looked like adding "scanner.nextLine()" will solve the problem but it didn't.

public class GameController {

private int numberOfPlayers = 2;

private Board board = new Board('.');
String players[] = new String[numberOfPlayers];
char playersMarkers[] = new char[numberOfPlayers];

public void getPlayersNames() {
    Scanner input = new Scanner(System.in);

    for (int i = 0; i < players.length; i++) {
        System.out.print("Insert player " + (i + 1) + "'s name: ");
        players[i] = input.nextLine();
    }
    input.nextLine(); // <- this one was suppose to solve the problem
    input.close();
}


public static void main(String[] args) {

    GameController gc = new GameController();
    gc.getPlayersNames();

    Scanner scanner = new Scanner(System.in);

    int array[] = new int[5];
    for (int i = 0; i < array.length; i++) {
        if (scanner.hasNext()) {
        array[i] = scanner.nextInt();
        }
    }

    scanner.close();

    for (int i = 0; i < array.length; i++) {
        System.out.println(array[i]);
    }

Output:

Insert player 1's name: John
Insert player 2's name: George
1
0
0
0
0
0

Upvotes: 1

Views: 114

Answers (1)

AlexRNL
AlexRNL

Reputation: 148

You are not getting anything from scanner (in the main method) because you already closed System.in (when closing input, at the end of the getPlayersNames method).

You should not close System.in yourself, as it prevent any future attempt to read from this stream.

Upvotes: 1

Related Questions