equals() using strings return true while the two variable are not

equals() using strings return true while the two variable are not

我的 android 应用程序有一个奇怪的问题。当上述方法为运行和answer_str = "When the activity is destroyed"questCHoiceStr = "When the user leave the activity."时。但是 if 条件 returns true 那真的是 st运行ge!

private QuestionChoice getSelectedQuestionChoice()
{
    int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
    RadioButton radioButton = (RadioButton)radioButtonGroup.findViewById(radioButtonID);
    if (radioButton != null)
    {
        String answer_str = radioButton.getText().toString();
        for (int i = 0; i < map.get(current_question).size(); i++)
        {
            List<QuestionChoice> questionChoiceList = map.get(current_question);
            QuestionChoice questionChoice = questionChoiceList.get(i);
            String questCHoiceStr = questionChoice.choice;
            if (questCHoiceStr.equals(answer_str));
            {
                return map.get(current_question).get(i);
            }
        }
        return null;
    }
    else
    return null;
}

我尝试添加 trim() 但没有任何改变... 我程序中使用的字符串是来自 xml 文件的字符串(可能与此有关)。 你知道是什么原因造成的吗? 谢谢

当您添加 ; 时,立即关闭。

if (questCHoiceStr.equals(answer_str)); <--

您的 if 并没有真正起作用,因为您立即关闭了它。

应该是

if (questCHoiceStr.equals(answer_str))

您当前的代码等于

if (questCHoiceStr.equals(answer_str)){

}
{
     return map.get(current_question).get(i);
}

为了避免这类问题,我强迫我的朋友们总是使用 {} :

尝试删除 if 语句中的分号。分号标记 if 语句的结尾,因此大括号 {} 之间的下一个块只是始终为 运行.

的代码
if (questCHoiceStr.equals(answer_str))
{
    return map.get(current_question).get(i);
}
private QuestionChoice getSelectedQuestionChoice()
    {
        int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
        RadioButton radioButton = (RadioButton)radioButtonGroup.findViewById(radioButtonID);
        if (radioButton != null)
        {
            String answer_str = radioButton.getText().toString();
            for (int i = 0; i < map.get(current_question).size(); i++)
            {
                List<QuestionChoice> questionChoiceList = map.get(current_question);
                QuestionChoice questionChoice = questionChoiceList.get(i);
                String questCHoiceStr = questionChoice.choice;
                **if (questCHoiceStr.equals(answer_str))**
                {
                    return map.get(current_question).get(i);
                }
            }
            return null;
        }
        else
        return null;
    }