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