-3
String firstanswer = scan.nextLine();
    if(firstanswer == answer2)
        {
            System.out.println("OK lets get started");
            }
    else
        {
            System.out.println("That is incorrect, of course you want to play");
            }

//answer2 is set to "yes", i declared it above

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
  • By the way, don't assume that your `if` statement is being ignored just because only your `else` is executing. Simply setting a breakpoint at the `if` statement would have shown you what was going on. – nhgrif Oct 03 '13 at 12:14
  • 2
    Each time I see `==` instead of `equals`... it ruin my day. – Maroun Oct 03 '13 at 12:15

3 Answers3

7

make it firstanswer.equals(answer2) instead of firstanswer == answer2.

When you want to check for equality of String in java then use equals method instead of == operator.

  • equals method checks whether the contents of String objects are same
  • == operator checks whether both the reference variables refer to same String object

To understand about strings and equality, read String comparison with equals and assignment operator It will help you understand the concept well.

Prasad Kharkar
  • 13,410
  • 5
  • 37
  • 56
1

Use equals() instead of == to compare strings.

Maroun
  • 94,125
  • 30
  • 188
  • 241
Simon Arsenault
  • 1,241
  • 11
  • 12
1

if(firstanswer.equals(answer2)) is what you're looking for.

firstanswer and answer2 are pointers to string objects. == checks to see whether the pointers are equal (whether they point to the same object), while equals() compares the contents of the two strings and returns a boolean representing whether or not the contents are equal.

Maroun
  • 94,125
  • 30
  • 188
  • 241
nhgrif
  • 61,578
  • 25
  • 134
  • 173