N
N
nolouds2021-12-18 17:44:44
Java
nolouds, 2021-12-18 17:44:44

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

1 answer(s)
D
Dmitry Roo, 2021-12-18
@nolouds

Strings in java are compared by method.equals()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question