Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

java - String is not equal to string?

String[] letters  = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "L"};

Scanner inp = new Scanner(System.in);
String input = (inp.nextLine());
String[] cord = input.split("");

for(int x = 0; x < 10; x++)
    if(letters[x] == cord[1])
        System.out.println("Fk yeah!");

Why the Fk yeah! never happens if I input one of A-L letters?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Strings are objects. The == compares objects by reference, not by their internal value.

There are 2 solutions:

  1. Use String#equals() method instead to compare the value of two String objects.

    if (letters[x].equals(cord[1]))
    
  2. Use char instead of String. It's a primitive, so == will work.

    char[] letters  = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'L'};
    
    Scanner inp = new Scanner(System.in);
    String input = (inp.nextLine());
    char[] cord = input.toCharArray();
    
    for (int x = 0; x < 10; x++)
        if (letters[x] == cord[1])
            System.out.println("Fk yeah!");
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...