My program displays an array of questions (question one-by-one). After I write an answer, an alert message should tell me whether my answer is right or wrong. The problem is that, even if I write the right answer the alert message displays a "false" message.
final String questions[] = {"Who's Tom?", "Who's Luca?", "Who's Flavie?"}
final String answers[] = {"American", "Italian", "French"}
// display question
answer_question.setOnClickListener(new View.OnClickListener() {
int CurrentQuestionIndex = 0;
public void onClick(View v) {
ask_question.setText(question[(CurrentQuestionIndex++) % (questions.length)]);
// discuss question versus answer
EditText answer = (EditText) findViewById(R.id.tvReponseF);
if (answer.equals(answers[CurrentQuestionIndex])) {
alertMessageRight();
} else {
alertMessageFalse();
}
}
});
The problem is that you're comparing an EditText
object with a String
field. You must compare String
with String
instead.
Here's how to do it:
String answer = ((EditText) findViewById(R.id.tvReponseF)).getText().toString();
if(answer.equals(answers[CurrentQuestionIndex]))
{
...
The problem is that you're increasing the index before actually checking if the answer's correct:
ask_question.setText(question[(CurrentQuestionIndex++) % (questions.length)]);
So the if the question index is 0, you'll get a question 0, then the question index will become 1 because of the ++
operator and you'll be reading the answer 1 instead of 0. I hope you understand this. What you need to do is remove the ++
from here and place it here:
if(answer.getText().toString().equals(answers[(CurrentQuestionIndex++) % (questions.length)]))
Because at this point, you'll read the proper answer and move on to the next index.
EDIT:
This was your biggest problem. Also you need to compare the answer.getText().toString()
as the other guys already noticed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With