0

I have an if statement within an if statement. Let me show the code first

    while(running)
    {
        System.out.println("Your current balance is: " + balance);
        System.out.println("How much would you like to gamble this round?");
        gamble = scan.nextInt();

        if(gamble > balance)
        {
            System.out.println("Error : Cannot gamble more than your balance");
            System.out.println("Enter a new bet less than " + balance);
            gamble = scan.nextInt();
        }

        System.out.println("Dealing cards...");
        if(deck >= 3)
        {
        card1 = rand.nextInt(12) + 2;
        card2 = rand.nextInt(12) +  2;
        card3 = rand.nextInt(12) + 2;
        deck = deck - 3;
        }
        else
        {
            System.out.println("Not enough cards left in the deck");
            System.out.println("Ending simulation...");
        }

        System.out.println("Your first card value is : " + card1);
        System.out.println("Your second card value is : " + card2);

        if(card1 == card2)
        {
            System.out.println("Same value for both cards! You win 2 chips!");
            balance = balance + 2;
            System.out.println("Play again? Type 'Y' for yes or 'N' for no");
            playAgain = scan.next();
            if(playAgain == "Y")
            {
                break;
            }
            else
            {
                running = false;
            }
        }

Where I put my break statement, I need it to return to the top of the while loop, but it is only breaking out of the one if statement. How can I go about the statement sending my code to the top of the while loop?

2 Answers2

0

change your if condition and instead of break, use continue.

    if(playAgain == "Y")
            {
                continue;// notice here i changed this to continue         
   }
Amit
  • 30,756
  • 6
  • 57
  • 88
0

break takes you completely out of a loop (for or while). It doesn't do anything to if or else blocks. you should use continue; instead.

continue ends this cycle of the loop and returns to the looping condition regardless of where you are in the loop (of course it only works on the innermost loop where you put it)

Matthew Ciaramitaro
  • 1,184
  • 1
  • 13
  • 27