如果选中所有复选框,为什么我的答案正确无误?

时间:2019-03-15 02:43:43

标签: java android checkbox

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

            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);

                }




        }
    });

} 

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您应该使用如下所述的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>

答案 2 :(得分:0)

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

使用代码显示后者:

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() || ...;
}
相关问题