如何解决 Java 扫描仪中的 NoSuchElementException 错误?

how to solve NoSuchElementException Error in Scanner of Java?

我正在制作一个简单的主机游戏,玩家可以在其中移动 x ,-x, y,-y 方向根据 String 从键盘收集的输入分别为 a, d, w 和 s , 但是扫描仪正在抛出 NoSuchElementException,我也尝试用 nextInt() 收集数据,但我遇到了类似的异常。 注意:但扫描仪只工作一次,即第一次。

我的代码

   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;

        }

    }

}

** 输出**

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

    }
}