Question

I have a method which should wait for the user to input a string to indicate which direction the player wants to move.

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

It always throws

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)

According to the API the Scanner.next() should block but is not waiting for the user to input a direction. What am I missing?

Was it helpful?

Solution

Closing the Scanner instance causes the underlying InputStream to be closed preventing input being read by subsequent calls. Remove the statement

scanner.close();

Read: Do not create multiple buffered wrappers on a single InputStream

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top