我正在编写测验应用。当我点击分数按钮以查看它是否有效时,它显示我有5分中的0分。我提出了所有正确的答案,但我的代码并没有提供任何结果。我错过了什么?我不知道还有什么可以添加,并且可以真正使用指导,因为我是一个新的编码器。我感谢您给予的任何帮助。
int correctAnswers = 0;
// Start score
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void answers(View view) {
RadioButton q1 = (RadioButton) findViewById(R.id.yes_radio_button);
Boolean q1RightAnswer = q1.isChecked();
if (q1RightAnswer) {
correctAnswers += 1;
}
CheckBox q2Box1 = (CheckBox) findViewById(R.id.box1_checkbox);
boolean q2Box1RightAnswer = q2Box1.isChecked();
CheckBox q2Box2 = (CheckBox) findViewById(R.id.box2_checkbox);
boolean q2Box2WrongAnswer = q2Box2.isChecked();
CheckBox q2Box3 = (CheckBox) findViewById(R.id.box3_checkbox);
boolean q2Box3RightAnswer = q2Box3.isChecked();
if (q2Box1RightAnswer)
if (q2Box3RightAnswer) {
correctAnswers += 1;
}
if (q2Box2WrongAnswer) {
correctAnswers += 0;
}
RadioButton q3 = (RadioButton) findViewById(R.id.shuri_radio_button);
Boolean q3RightAnswer = q3.isChecked();
if (q3RightAnswer) {
correctAnswers += 1;
}
RadioButton q5 = (RadioButton) findViewById(R.id.two_radio_button);
Boolean q5RightAnswer = q5.isChecked();
if (q5RightAnswer) {
correctAnswers += 1;
}
EditText q4 = (EditText) findViewById(R.id.wakanda);
String q4RightAnswer = q4.getText().toString();
if (q4RightAnswer.equals(correctAnswers)) {
correctAnswers += 1;
} else {
// incorrect, do nothing
}
}
/**
* This method is called when the score button is clicked.
*/
public void submitScore(View view) {
Button nameField = (Button) findViewById(R.id.score);
String score = nameField.getText().toString();
// Show score message as a toast
Toast.makeText(this, "You got " + correctAnswers + "/5 correct!", Toast.LENGTH_LONG).show();
// Exit this method early because there's nothing left to do
return;
}
}
答案 0 :(得分:1)
这永远不会成真
q4RightAnswer.equals(correctAnswers)
您需要比较匹配类型,而不是字符串与整数。
假设您正在尝试执行的操作,请解析字符串或将int转换为String。
如果没有标记任何复选框或从未调用answers()
,则您将打印零。例如,answers方法和submitScore方法之间的区别是什么?两者都采用View参数,哪一个实际分配给click事件?
我建议做类似
的事情RadioButton q1, q3, q5;
EditText q4;
Checkbox qBox1, qBox2;
Button submit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
q1 = (RadioButton) findViewById(R.id.yes_radio_button);
// assign other views here
submit = (Button) findViewById(R.id.score);
submit.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
int correctAnswers = 0;
if (q1.isChecked()) correctAnswers += 1;
// TODO: check other inputs
String q4Text = q4.getText().toString();
if (q4Text.equals(String.valueOf(correctAnswers)) {
correctAnswers += 1;
}
// Toast correct answers
}
});
}
基本上,将所有视图定义为类级变量,然后在内容视图可用后立即设置它们,然后仅在单击按钮时计算分数(换句话说,等待用户输入)。此外,每次单击按钮时重置分数。