Answer the question
In order to leave comments, you need to log in
Why doesn't comparing two strings work in a for loop?
I enter "a" or b or c on the English keyboard, the program should output "1". But the code doesn't work, namely the if inside the for loop. It gives me -1 for any input. What's wrong?
public static void main(String[] args) {
try (Scanner myObj = new Scanner(System.in)) {
String s = myObj.nextLine();
String ans = "-1";
String[] x = { "a", "b", "c" };
for (String i : x) {
if (s == i) { // не срабатывает
ans = "1";
}
}
System.out.println(ans);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question