This question already has an answer here:
- How do I compare strings in Java? 23 answers
I'm expecting isCorrect() method to return "true", because it should have all the conditions to reach that answer, but it only return "false" (many times at that according to the console). There are errors but I have no idea what they are. Please tell me what's going so wrong with this code.
public class BooleanMethodTest {
static int num1 = 1;
static int num2 = 2;
static int num3 = 3;
public static void main(String[] args) {
// it should print "true" but I get "false" instead
System.out.println(isCorrect("s1"));
}
public static boolean isCorrect(String s) {
boolean answer = false;
// step 1
if (s == "s1") {
if (num1 == 1) {
isCorrect("s2");
} else {
System.out.println("else1");
}
}
// step 2
else if (s == "s2") {
if (num2 == 2) {
isCorrect("s3");
} else {
System.out.println("else2");
}
}
// step 3
else if (s == "s3") {
if (num3 == 3) {
// the method should return true here
answer = true;
} else {
System.out.println("else3");
}
}
System.out.println(answer);
return answer;
}
}
Aucun commentaire:
Enregistrer un commentaire