0

Trying to make a pause in a game with the idea of if he wants to quit the game or roll the dice.

I added a scanner for user input: if 1 quit game, if anything else continue;

When I try to play it crashes at the scanner point with the exception: Exception in thread "main" java.util.NoSuchElementException ( at stopGame = sc.nextInt(); , showed the line in code) The code: `

public static void playersTraverse(int playerCount, int mapLength)
{


    int diceRollAmount;
    int[] player = new int[playerCount];
// --------------------------


        for(int i = 0; i<playerCount; i++)
            player[i] = 0;

    System.out.println("Player Positions: ");

        for(int i = 0; i<playerCount;i++)
            System.out.println((i+1) + " Player is at position " + (player[1]+1));
    Scanner sc = new Scanner(System.in);

    Integer stopGame=0;
    while (player[0] != (mapLength-1) || player[1] != (mapLength-1) || player[2] != (mapLength-1))
    {
        for(int i = 0;i< playerCount; i++)
        {
            System.out.println(i + " player it's your turn!   (if you want to stop press 1)");

            boolean hasNextInt = false;
            while(!hasNextInt){
                hasNextInt = sc.hasNextInt();
                stopGame = sc.nextInt(); // <--- Crashes here;

                if(stopGame.equals(1))
                {
                    System.exit(0);
                }

                sc.close();
                diceRollAmount= rollDice();
                System.out.println("It's " + diceRollAmount);
                player[i] += diceRollAmount;
                player[i] = gameMap.get(player[i]).checkElements(player[i]);
                System.out.println("Player " + (i+1) + " is at the " + (player[i]+1) + " pos.");

                if(player[i] >= mapLength-1)
                    winGame(player[i]);
            }

        }
        System.out.println();
    }
}

`

I tried to do just with nextLine but says there is no line found, found that I need to make a while loop and still crashes.

How do I use scanner in this case so it does not crash?

the full code: https://github.com/QikKick/Uni-work/tree/main/Snakes%20and%20Ladders

Qikee
  • 1
  • 2
  • Please consider creating and posting a valid [mre]. The link will explain what this is and how it can help you and us. – Hovercraft Full Of Eels Nov 20 '22 at 19:28
  • 2
    1) INDENTATION - that code is mostly not readable; 2) closing the `Scanner` also close `System.in` -> nothing more can be read from it (from its [documentation](https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/util/Scanner.html#nextInt()): "`NoSuchElementException` - if input is exhausted") – user16320675 Nov 20 '22 at 19:40

0 Answers0