使用多个扫描仪失败 - Java

时间:2015-12-09 17:51:24

标签: java input java.util.scanner

我的Scanner类有问题。我有一些方法可以读取用户的某些输入,但是在调用第一个方法后其他人崩溃(无法读取输入)。我搜索了解决方案,它看起来像添加" scanner.nextLine()"将解决问题,但它没有。

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]);
    }

输出:

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

1 个答案:

答案 0 :(得分:1)

您没有从scannermain方法)获得任何内容,因为您已在{{1}结束时关闭了System.in(关闭input时方法)。

您不应该自己关闭getPlayersNames,因为它会阻止将来尝试从此流中读取。