user3505003
user3505003

Reputation: 55

editing the while loop

I have a while loop in my video poker java game. I'm using this loop to ask the player whether they want to keep the current cards in their hand. There's another while loop inside the first one that asks the player to enter a valid answer in case their entered anything other than "yes" or "no." For some reason, it skips every other card in the hand. For instance, it will say, "Do you want to keep card number 1?" Then I press yes/no, and it asks next, "Do you want to keep card number 3?" instead of number 2. Can you help me figure out why this is happening, please?

int i = 1;
while (i < 6)
{
    System.out.println("Would you like to keep the card number " + i + "?");
    System.out.println("Enter yes or no");
    String answer = input.next();
        while((!answer.equals("yes")) && (!answer.equals("no")))
        {
            System.out.println("Please enter a valid answer");
            answer = input.next();
        }

        if (answer.equals("yes"))
        {
            toKeep.add(p.getHand().get(i-1));
            i++;
        }
        else if (answer.equals("no"));
        {
            i++;
        }

        }

Upvotes: 1

Views: 85

Answers (2)

CMPS
CMPS

Reputation: 7769

First you added a semicolon at the end of the else if condition,

Second you should put an input.nextLine() before closing the while loop.

Here's the final code:

while (i < 6)
{
    System.out.println("Would you like to keep the card number " + i + "?");
    System.out.println("Enter yes or no");
    String answer = input.next();
        while((!answer.equals("yes")) && (!answer.equals("no")))
        {
            System.out.println("Please enter a valid answer");
            answer = input.next();
        }

        if (answer.equals("yes"))
        {
            toKeep.add(p.getHand().get(i-1));
            i++;
        }
        else if (answer.equals("no"))
        {
            i++;
        }
        input.nextLine(); // JUNK
}

Upvotes: 0

robertoia
robertoia

Reputation: 2361

You have this:

else if (answer.equals("no"));
{
     i++;
}

If the answer equals no it ends the statement (semicolon). Then it executes the block i++, no matter what the answer was.

Where you should have:

else if (answer.equals("no"))
{
     i++;
}

If the answer equals no it executes block i++

Upvotes: 3

Related Questions