如果我选择所有复选框,为什么会将我的答案显示为正确



我有四个复选框以及一个显示问题的文本视图。我正在尝试使用复选框创建一个简单的多项选择测验。如果他们选择正确的答案,我设法向用户展示敬酒。如果他们选择一个错误的答案,则敬酒。我遇到的问题是,如果用户选择所有答案,它被认为是正确的。有人可以帮我弄这个吗。结果变量将复选框存储为字符串,我将其与正确的答案进行了比较。

            if(result1 == firstQuestion.getCorrectAnswer() && result2 == firstQuestion.getSecondCorrectAnswer()){
                    currentScore = currentScore + 1 + userScore;
                    Intent i = new Intent(CheckBoxQuestions.this, ResultScreen.class);
                    i.putExtra("finalScore",currentScore);
                    startActivity(i);
                }else{
                    Toast.makeText(CheckBoxQuestions.this, "Incorrect", Toast.LENGTH_SHORT).show();
                    currentScore = currentScore + 0 + userScore;
                    Intent i = new Intent(CheckBoxQuestions.this, ResultScreen.class);
                    i.putExtra("finalScore",currentScore);
                    startActivity(i);
                }


        }
    });
} 

您正在比较 ==的字符串的结果。==操作比较了两个对象的引用(或原始对象的值)。由于字符串是对象,因此不建议使用==进行比较。改用.equals()方法。<String>.equals(<other String>) Object中定义的.equals()方法与==相同。但是,在字符串的情况下,许多对象(例如字符串覆盖.equals()),以比较字符。

您应该使用radiogroup和radiobutton,如下所述,它将允许您仅选择一个单选按钮,这只是一个答案。无线电按钮将位于单个无线电组中。

<RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:text="Radio Button 1"/>
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Radio Button 2"/>
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Radio Button 3"/>
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Radio Button 4"/>
</RadioGroup>

一个优雅的解决方案是使用按钮组在问题的情况下仅允许一个选择。如果用户应该能够选择不同的解决方案(可能有几个答案是正确的),那么您可能应该倒转测试。这是用户没有错误回答的测试。

用代码显示后者:

if(isCorrectAnswers(firstQuestion) && !hasIncorrectAnswer(firstQuestion)) {
    ... // React for correct answer
} else {
    ... // React for incorrect answer
}

private boolean isCorrectAnswers(AnswerSelectionChoice choice) {
    return choice.isSelectedCorrectChoice() && isSelectedSecondCorrectChoice() && ...;
}

private boolean hasIncorrectAnswer(AnswerSelectionChoice choice) {
    return choice.isSelectedIncorrectChoice() || isSelectedSecondIncorrectChoice() || ...;
}

最新更新