javaexceptionjava.util.scannernosuchelementexception

how to solve NoSuchElementException Error in Scanner of Java?


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)

Solution

  • 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;
            }
    
        }
    }