Scanner.next()没有阻塞

时间:2014-05-02 18:43:33

标签: java java.util.scanner

我有一个方法应该等待用户输入一个字符串来指示玩家想要移动的方向。

private static void makeMoves(java.awt.Point playerPosition,
        java.awt.Point snakePosition) {
    Scanner scanner = new java.util.Scanner(System.in);
    String move = scanner.next();
    switch (move.charAt(0)) {
    case 'h':
        if (playerPosition.y == 0) {
            playerPosition.y = 9;
        } else {
            playerPosition.y = Math.max(0, playerPosition.y - 1);
        }
        moveSnake(playerPosition, snakePosition);
        break;
    case 'u':
        if (playerPosition.y == 9) {
            playerPosition.y = 0;
        } else {
            playerPosition.y = Math.min(9, playerPosition.y + 1);
        }
        moveSnake(playerPosition, snakePosition);
        break;
    case 'l':
        if (playerPosition.x == 0) {
            playerPosition.x = 9;
        } else {
            playerPosition.x = Math.max(0, playerPosition.x - 1);
        }
        moveSnake(playerPosition, snakePosition);
        break;
    case 'r':
        if (playerPosition.x == 39) {
            playerPosition.x = 0;
        } else {
            playerPosition.x = Math.min(39, playerPosition.x + 1);
        }
        moveSnake(playerPosition, snakePosition);
        break;
    }
    scanner.close();
}

总是抛出

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:907)
at java.util.Scanner.next(Scanner.java:1416)
at ZZZZZnake.makeMoves(ZZZZZnake.java:52)
at ZZZZZnake.main(ZZZZZnake.java:45)

根据API,Scanner.next()应该阻止但不等待用户输入方向。我错过了什么?

1 个答案:

答案 0 :(得分:3)

关闭Scanner实例会导致基础InputStream被关闭,防止后续调用读取输入。删除声明

scanner.close();

阅读:Do not create multiple buffered wrappers on a single InputStream