Java键盘输入匹配异常:输入'switch horses'未触发预期输出
Hey there, let's break down why your keyboard input logic isn't triggering the expected "Correct" message when you type the right phrase.
The Core Issue: String Comparison with ==
In Java, using == to compare strings checks if the two string objects refer to the same memory location, not if their actual content matches. Even if your Code variable holds the exact text "switch horses", it's a separate object instance from the literal string "switch horses" in your condition—so == will always return false here.
The Fix: Use equals() for Content Comparison
Replace the == check with the equals() method, which compares the actual text content of the strings. For extra safety (to avoid a NullPointerException if Code is ever null), you can even flip the comparison to call equals() on the literal string:
if(Game.gameRoom == Room.RoomThree){ if(key != KeyEvent.VK_SPACE){ keycode = e.getKeyCode(); Code += KeyEvent.getKeyText(keycode); Code = Code.toLowerCase(); System.out.println(Code); // Fixed comparison here if("switch horses".equals(Code)){ handler.addObject(new KeysBtn(300, 385, ID.Key)); System.out.println("Correct"); Code = ""; } } }
Quick Additional Check
Double-check that your input doesn't accidentally include extra spaces or typos when you type "switch horses"—since you're converting everything to lowercase, case won't be an issue, but stray spaces could throw off the match.
内容的提问来源于stack exchange,提问作者Cory

