java.util.NoSuchElementException 使用扫描仪时

java.util.NoSuchElementException when using a scanner

所以在调用一个函数(在我的主函数中)后,我将在下面 post

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)

将我链接到此代码的最后一行:

    int numHouse = 0;
    int numSeed = 0;
    System.out.println("Enter the total number of houses on the board: ");
    Scanner houseInput = new Scanner(System.in);
    numHouse = houseInput.nextInt();

它在我调用该函数之后立即放置(稍后我会在上面的代码中关闭扫描仪)。当我注释掉调用该函数时,此扫描仪可以正常工作,因此函数中的某些内容会导致扫描仪出错。我花了几个小时寻找但无法解决它,如果有人可以的话,我将不胜感激。函数:

    public void InitializePlayers() {
    //change numPlayers to variable that contains number of players
    boolean validInput = false;
    do {
        System.out.print("Enter Number of Players (1/2): ");
        Scanner userInput = new Scanner(System.in); 
        int numPlayers = userInput.nextInt();
        System.out.print("\n");
        if(numPlayers == 1) {
            //One Human Player, One AI Player
            System.out.println("Single Player Selected");
            validInput = true;
            System.out.print("\n");             
            System.out.print("Enter Player One Name: ");

            //Initialize Player 1
            String p0_name = userInput.next();
            Player Human1 = new Player(p0_name,0,false);
            this.setPlayer0(Human1);

            //Initialize AI
            String AI_name = "Hal";
            Player AI = new Player(AI_name,1,true);
            this.setPlayer1(AI);
            userInput.close();
        }
        else if(numPlayers == 2){
            //Two Human Players
            System.out.println("Two Players Selected");
            validInput = true;
            System.out.print("Enter Player One Name: ");

            //Initialize Player 1
            String p0_name = userInput.next();
            Player Human1 = new Player(p0_name,0,false);
            this.setPlayer0(Human1);

            //Initialize Player 2
            System.out.print("Enter Player Two Name: ");
            String p1_name = userInput.next();
            Player Human2 = new Player(p1_name,0,false);
            this.setPlayer1(Human2);
            userInput.close();
        }
        else {
            System.out.println("Error, Player 1 Not set!");
            userInput.close();
        }
    }while(!validInput);
}

(我测试的时候总是输入2)我试过去掉do-while循环,但是并没有解决问题。谢谢

如果可以使用一个扫描器从 System.in 读取整个应用程序就更好了

关闭获取玩家的扫描器将关闭 InputStream,这将导致此 NoSuchElmentException.Better 如果您可以定义一个扫描器并在获取输入的两种情况下都使用它

正如对方所说,我终于找到问题所在了。关闭扫描器一旦关闭了 InputStream,就不能再次使用它。我必须在我的 main 开始时制作一个扫描仪并将它传递给所有需要它的功能。我删除了每个函数的所有关闭,并在 main 结束时关闭。