0

I'm writing a video poker in java, and I need to ask the player if the want to remove any cards from their hand. I wrote a while loop for that, but it is not working the way it's supposed to right now. I'd appreciate if someone could send me in the right direction--I'm still new to java.. Thanks. (the counter is there so that the player doesn't remove more than 5 cards)

    String response = "y";
    int counter = 0;
    System.out.println("Remove any cards?");
    System.out.println("Enter y for 'yes' and n for 'no'");
    response = input.nextLine();
    while((response != "n") && (counter < 5))
    {

        System.out.println("Enter the number of a card to be removed (1-5)");
        int l = input.nextInt();
        p.removeCard(p.getHand().get(l-1));
        p.addCard(cards.deal());
        cards.incrementTop();
        counter ++;
        System.out.println("Card removed. More? Type 'yes' or 'no'");
        String answer = input.nextLine();
        if (answer == "no")
            {
                response = "n";
            }       
    }  
1
  • 1
    What way is it working right now, and how does it differ from how it's "supposed" to work? Commented Apr 7, 2014 at 16:04

2 Answers 2

5

You can't compare Strings using != or ==.

Use .equals()

while(!("n".equals(response)) && (counter < 5))

The same here too

if (answer == "no")

Other things to improve

  • The user could write "no" the first time and how it's done right now it could not work
    • You ask to the user to write "no" but you check for "n"
  • What about N? Y?
  • What about nO? NO? (Hint: search .equalsIgnoreCase())

Another hint for you: Use a boolean variable for yes/no, is better and more easy :)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I always forget that about strings. But I don't understand why after asking if the player wants to remove more cards it doesn't wait for the answer and goes straight to the 1st line of the loop again. Why does this happen?
2

Try using the String.equals() method to compare strings. Your while loop should be

 while(( !response.equals( "n" )) && (counter < 5))
  {
       //do Something 
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.