You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java键盘输入匹配异常:输入'switch horses'未触发预期输出

Why Your "switch horses" Check Isn't Working

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:23:53