为什么简单的字符串比较给出FALSE结果?

时间:2016-04-22 18:50:25

标签: java android if-statement

我将一个对象转换为JSONObject,然后获取该字符串并将其与" play_audio进行比较。"即使我的日志给了我正确的字符串,IF语句也会给出错误的结果 - 发生了什么?

                JSONObject data = (JSONObject)args[0];
                String command = null;
                try {
                    command = data.getString("command");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "<<<<---- RECEIVING COMMAND ----->>> " + command);
                if (command == "ping_audio") { //WHY IS THIS FALSE?
                    Log.i(TAG, "<<<<---- PLAYING AUDIO ----->>> ");
                }

logcat的

<<<<---- RECEIVING COMMAND ----->>> ping_audio

1 个答案:

答案 0 :(得分:1)

尝试使用String.equals()方法 像command.equals(“ping_audio”)

if (command.equals("ping_audio") {    // should give you what you want
     Log.i(TAG, "<<<<---- PLAYING AUDIO ----->>> ");
}