-1

Having a slight problem with the following block of code:

newusr = c.readLine("New user? ");
if (newusr == "y") {
    System.out.println("IF");
    usnm = createNewUser();
    usnm = loginToClient();
}
else {
    System.out.println("ELSE");
    usnm = loginToClient();
}

Basically, when i enter the single character "y" to the prompt, it takes me to the else case and thusly straight to the loginToClient method. What's going on; is the "y" in a different encoding or something?

c is a console.

gossfunkel
  • 257
  • 2
  • 4
  • 13
  • Try outputting newusr to the screen, what do you see? Just for fun, try outputting the length of newusr. You might be surprised. – Tremmors May 29 '12 at 15:48
  • `==` compares two references to an object i.e. are they the same object. `.equals()` can conmpare the *contents* of two objects. – Peter Lawrey May 29 '12 at 15:48

3 Answers3

1

to campare Strings in java you use equals, like this:

...
if (newusr.equals("y"))
...
Euclides Mulémbwè
  • 1,677
  • 11
  • 18
  • I feel so stupid, thanks. I actually knew I should have used this, I don't know why i didn't or didn't see this... – gossfunkel May 30 '12 at 14:25
0

Why dont you do a if(("y").equals(newusr)) and check?

This will also avoid NullPointerException if you do not enter a value.

JHS
  • 7,761
  • 2
  • 29
  • 53
0

The code newusr == "y" will compare the memory location of newusr variable with "y". Which will fail.

You should be comparing the objects using .equals() method.

Ramesh PVK
  • 15,200
  • 2
  • 46
  • 50