moody
moody

Reputation: 402

Scanner() not working with if - else statement

My intention is to let the user decide which method to use by cheking its input.

I have the following code:

try {
        String test = scan.next();
        if(test == "y") {
            //do stuff

        }
        else if (test == "n") {
            //do stuff
        }
    } catch (Exception e) {
        System.out.println("false");
    } 

I tried to analyze with the debugger. It is not jumping in the if-statement. can you help me out here?

Upvotes: 1

Views: 78

Answers (1)

Mekap
Mekap

Reputation: 2085

You need to use equals to compare strings

if(test == "y") 

becomes

if (test.equals("y")) 

Same for "n" obviously.

== test for reference equality, but you're looking for value equality, that's why you should use equals, and not ==.

Upvotes: 2

Related Questions