2

This code is a snippet from a Blackjack game I'm making. No matter what I enter, the program never breaks out of a loop.

boolean bool = true;
do{
    Scanner kb = new Scanner(System.in);
    String choice = kb.next();
    if(choice == "Hit" || choice == "hit") {
        String action = "hit";
        bool = false;
    } else if(choice == "Stay" || choice == "stay") {
        String action = "stay";
        bool = false;
    } else {
        System.out.println("Do not recognize response. Retry.");
    }
} while (bool == true);

What normally happens: http://puu.sh/87KZk.png

Any help would be appreciated. Thanks!

Saro Taşciyan
  • 5,210
  • 5
  • 31
  • 50
Dan Appel
  • 17
  • 1
  • 6
  • 4
    Don't compare strings in Java using `==`. See http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – helderdarocha Apr 14 '14 at 00:38

1 Answers1

5

You are comparing strings with ==. In Java we compare strings with .equals() instead.

You can do something like this:

boolean bool = true;
do {
    Scanner kb = new Scanner(System.in);
    String choice = kb.next();
    if(choice.equals("Hit") || choice.equals("hit")) {
        String action = "hit";
        bool = false;
    } else if(choice.equals("Stay") || choice.equals("stay")) {
        String action = "stay";
        bool = false;
    } else {
        System.out.println("Do not recognize response. Retry.");
    }
} while (bool == true);

I also formatted some parts of your code for clarity. As suggested in the comments below, you can also use equalsIgnoreCase to compare string regardless of their capitalization.

Hope this helps!

nmenego
  • 846
  • 3
  • 17
  • 36