0

I have the following code which is attached to my window. Whenever the user presses a keyboard, that character is saved to a 8 character long array in a StringBuilder class.

When the user types "somecode" then the something() method should be called.

static StringBuilder    s   = new StringBuilder("aaaaaaaa");

public static void listen() {

     Main.sc.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent event) {
                {
                    for(int i=0; i<7; i++) {
                        s.setCharAt(i, s.charAt(i+1)); // the characters move 1 position backwards
                    }    
                    char c = event.getText().charAt(0);
                    s.setCharAt(7, c);

                    System.out.println(s.toString());

                    if(s.toString()=="somecode") {
                        System.out.println("--------------------------");
                        something();
                    }
                }
            }
        });
}

My output is:

aaaaaaas
aaaaaaso
aaaaasom
aaaasome
aaasomec
aasomeco
asomecod
somecode

However the something() method is never called, nor is the "-----------------" displayed.

EDIT: This has been tagged as duplicate, however .equals() is not working either

if(s.equals("somecode")) {
                        System.out.println("--------------------------");
                        something();
                         }
Hydraxia
  • 81
  • 2
  • 9
  • 2
    Use equals() when comparing String objects – Shredator Sep 13 '18 at 08:18
  • 2
    Use `s.toString().equals(...);`. – SedJ601 Sep 13 '18 at 13:40
  • `s` is a `StringBuilder` object, not a `String`. Therefore, when you try to compare `s.equals("somecode")`, Java is rightly stating "This `StringBuilder` does not equal the `String` 'somecode'." As Sedrick mentioned, you need to get the `String` contents from the `StringBuilder` first... – Zephyr Sep 14 '18 at 05:34

0 Answers0