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?
The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.
Note: When comparing two strings in java, we should not use the == or != operators. These operators actually test references, and since multiple String objects can represent the same String, this is liable to give the wrong answer.
Unfortunately, it's easy to accidentally use == to compare strings, but it will not work reliably. Remember: use equals() to compare strings. There is a variant of equals() called equalsIgnoreCase() that compares two strings, ignoring uppercase/lowercase differences.
The major difference between the == operator and . equals() method is that one is an operator, and the other is the method. Both these == operators and equals() are used to compare objects to mark equality.
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!");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With