+ 3

Wrote to this code to break out of a while loop. Doesn't seem to be working and I cannot find any error with it.

String usercont = lat.next(); if (usercont == "yes"){ System.out.println("Program is now exiting"); break; } else if (usercont == "no"){ continue; }

6th Oct 2017, 8:20 PM
Toni Sedjoah
Toni Sedjoah - avatar
5 ответов
+ 10
The issue could be that you are using == for strings. == does not compare equality for objects, it compares memory location. If you are taking input this could be an issue. Use equals(String) instead. Example/ if(userCont.equals("no"))
6th Oct 2017, 8:25 PM
Rrestoring faith
Rrestoring faith - avatar
+ 15
Many possible issues... It's hard to tell without the full code, but here are some ideas: - play it safe - compare strings with the equals method (I'd bet on that!) - uppercase/lowercase isn't checked - what should continue do? I can't see no loop...
6th Oct 2017, 8:26 PM
Tashi N
Tashi N - avatar
+ 4
@Rrestoring faith you taught me this when i first started 😜
6th Oct 2017, 11:02 PM
D_Stark
D_Stark - avatar
+ 3
For String use "equals". == checks for reference similarity, equals value similarity
6th Oct 2017, 8:28 PM
Timo
Timo - avatar
+ 1
Followed the same procedure with int and it worked perfectly but having some challenges with String
6th Oct 2017, 8:21 PM
Toni Sedjoah
Toni Sedjoah - avatar