0

I am making a simple console game where player is allowed to move in x ,-x, y,-y directions according to String input collected from keyboard as a, d, w and s respectively , but scanner is throwing NoSuchElementException, I tried collecting data with nextInt() too ,but I was getting similar exception. Note: But scanner works for one time i.e. first time.

My Code

   private static void gamePlay(boolean isPlaying) {

    while (isPlaying) {

        System.out.println("Choose a, d , s or w for movement:");
        Scanner sc = new Scanner(System.in);
        String choice = sc.next();
        sc.close();
        // code for movement of player according to a or s or d or w
        switch (choice) {
            case "a":
                // Some code here
                // move -x
                break;

            case "d":
                // Some code here
                // move +x

                break;

            case "w":
                // Some code here
                // move +y

                break;

            case "s":
                // Some code here
                // move -y

                break;
            case "q":
                //quit 
                isPlaying = false;
                break;

            default:
                break;

        }

    }

}

** Output**

    Choose a, d , s or w for movement:
    a
    Choose a, d , s or w for movement:
    Exception in thread "main" java.util.NoSuchElementException
    at java.base/java.util.Scanner.throwFor(Scanner.java:937)
    at java.base/java.util.Scanner.next(Scanner.java:1478)
    at App.gamePlay(App.java:37)
    at App.main(App.java:17)

1 Answers1

0
private static void gamePlay(boolean isPlaying) {

    while (isPlaying) {

        System.out.println("Choose a, d , s or w for movement:");
        Scanner sc = new Scanner(System.in);
        String choice = sc.next();
        // code for movement of player according to a or s or d or w
        switch (choice) {
            case "a":
                // Some code here
                // move -x
                break;

            case "d":
                // Some code here
                // move +x

                break;

            case "w":
                // Some code here
                // move +y

                break;

            case "s":
                // Some code here
                // move -y

                break;
            case "q":
                //quit
                sc.close();
                isPlaying = false;
                break;

            default:
                break;
        }

    }
}
rlowell
  • 66
  • 5
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 13 '22 at 04:49