0
while (true) {           
    try {
        System.out.println("Choose a player or type quit: Nirvaan(" + player1.getMoney() + ") or Faris(" + player2.getMoney() + ")");
        String chosenPlayer = scanner.nextLine();

        if (chosenPlayer.equalsIgnoreCase("quit")) {
            break;
        }

        Player player = null;
        if (chosenPlayer.equalsIgnoreCase(player1.getName())) {
            player = player1;
        } else if (chosenPlayer.equalsIgnoreCase(player2.getName())) {
            player = player2;
        }
       
        System.out.println("Which game would " + player.getName() + " like to play? ");
        System.out.println("1. Balloon Darts");
        System.out.println("2. Ring Toss");
        System.out.println("3. Break a Plate");
        System.out.println("4. Quit");
        System.out.print("> "); 
       
        int choice = scanner.nextInt();

        // Check if the user chose to quit
        if (choice == 4) {
            break;
        }        

        // Get the chosen game
        GameBooth game = games.get(choice - 1);        
        
        // Let the players play the game
        System.out.println(player.getName() + " goes to " + game.getName());
        game.playGame(player);
        
    } catch (Exception e) {
        
    }
}

OUTPUT//

Choose a player or type quit: Nirvaan(5.0) or Faris(3.0)
nirvaan
Which game would Nirvaan like to play? 
1. Balloon Darts
2. Ring Toss
3. Break a Plate
4. Quit
> 1
Nirvaan goes to Balloon Darts
Nirvaan won a Sticker
Choose a player or type quit: Nirvaan(3.0) or Faris(3.0)
Choose a player or type quit: Nirvaan(3.0) or Faris(3.0)

I tried moving the choose player line out of the try statment but that did not work, it kept on doing the same thing.

azro
  • 53,056
  • 7
  • 34
  • 70
  • 2
    Mybe you get an exception in the first run, **Never catch Exceptions** without handle it. Atleast log them – Jens Dec 09 '22 at 07:23
  • Move the "quitting" part to the end of the loop and break it there – XtremeBaumer Dec 09 '22 at 07:26
  • Don't do `scanner.nextInt()`, but `Integer.parseInt(scanner.nextLine())` that'll wave you from unread return-line char – azro Dec 09 '22 at 07:29
  • Your code is throwing a NullPointerException, which you don't see because you catch and ignore exceptions. This happens because `nextInt()` doesn't consume the new line, which means the `nextLine()` reads an empty string, which means `player` remains `null`, which then causes the NPE when you dereference `player` with `player.getName()`. And because you ignore exceptions, the loop restarts – Mark Rotteveel Dec 09 '22 at 08:28

0 Answers0