简体   繁体   中英

I am getting this runtime error in java: java.util.NoSuchElementException, and I'm not sure how to fix it

I am creating a tic tac toe game in java for a homework assignment. I have a parent class called TicTacToe and a derived class called humanVsHuman.

The following method is written in the derived class. It prompts the user to enter the position that they want to enter their game piece (X or O) and then calls two methods from the parent class: One that stores the X or O in a multidemensional array called setGb() and one that displays the board with the new piece called displayBoard().

Here is the method:

private void playGame() {
    Scanner keyboard = new Scanner (System.in);
    int row, col;
    System.out.println("When playing, enter the row and column position for your X or O piece separated by a space.");
    do{
        System.out.print(player1 + ", Enter X position: ");
        row = keyboard.nextInt();
        col = keyboard.nextInt();
        setGb(row, col, 'X');
        displayBoard();

        System.out.print(player2 + ", Enter O position: ");
        row = keyboard.nextInt();
        col = keyboard.nextInt();
        setGb (row, col, 'O');
        displayBoard();
        keyboard.close();
    } while (!gameOver());
}

I am getting the following runtime error:

When playing, enter the row and column position for your X or O piece separated by a space.
Deena, Enter X position: Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at Assignment7C.HumanVsHuman.playGame(HumanVsHuman.java:38)
    at Assignment7C.HumanVsHuman.repeatGame(HumanVsHuman.java:28)
    at Assignment7C.HumanVsHuman.game(HumanVsHuman.java:14)
    at Assignment7C.TicTacToeTest.main(TicTacToeTest.java:10)

I'm getting the error as soon as the prompt to enter the position is displayed and before I am able to input the position.

Thanks in advance for your help.

Move keyboard.close() out of the loop. You don't want to close the Scanner until the game is over. This will not resolve the exception in your problem, but you need to do it anyway to avoid the very next problem you will face.

Did you try removing the following code from your while loop and see if it works.

    keyboard.close();

Or you can add it outside the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM