Reputation: 21759
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?
Upvotes: 11
Views: 43148
Reputation:
To compare Strings for equality, don't use ==. The == operator checks to see if two objects are exactly the same object. Two strings may be different objects, but have the same value (have exactly the same characters in them). Use the .equals() method to compare strings for equality. Similarly, use the .compareTo() method to test for unequal comparisons. For example,
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t) // ILLEGAL
if (s.compareTo(t) > 0) // CORRECT>
Upvotes: 11
Reputation: 1109655
Strings are objects. The ==
compares objects by reference, not by their internal value.
There are 2 solutions:
Use String#equals()
method instead to compare the value of two String
objects.
if (letters[x].equals(cord[1]))
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!");
Upvotes: 24