Search code examples
javafxcontrollerfxmlscenebuilder

if statement returns wrong output when comparing KeyEvent .getText and index in array javafx


I am trying to check if input (in the form of keypresses) from the user is the same as string textToType which has been broken down into a character array. The problem is even though they both return the same value, when I compare them it will still give the output wrong letter.

Output

index splitter [0] returned: t
event.getText returned: t
wrong letter
@FXML
private void detectInputAreaKeyEvent(KeyEvent event) {
    char[] splitter = textToType.toCharArray();

    System.out.println("index splitter [0] returned: " + splitter[0]);
    System.out.println("event.getText returned: " + event.getText());

    if (event.getText().equals(splitter[0])) {
        System.out.println("right letter");
    }
    else {
        System.out.println("wrong letter");
    }

Solution

  • TLDR: you are comparing a String to a char, so they are not equal.


    KeyEvent.getText() returns a String, and splitter[0] is the primitive type char.

    Since String.equals(...) expects an Object, so when you call

    event.getText().equals(splitter[0])
    

    splitter[0] is autoboxed to a wrapper object of type Character. Consequently, you are comparing a String to a Character. The String.equals() documentation states

    The result is true if and only if the argument is not null and is a String object ...

    (my emphasis). Since you're providing a Character instance, not a String instance, the result of equals() is false.

    You can fix this by comparing things of the same type:

    if (event.getText().charAt(0) == splitter[0])
    

    or

    if (event.getText().equals(textToType.substring(0,1)))
    

    (the first probably being marginally more efficient).