Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String arrays does not match

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();
        }
    } 
});
like image 790
Tanguy MP Avatar asked Jul 08 '16 19:07

Tanguy MP


2 Answers

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]))
{
     ...
like image 146
Carlo Avatar answered Sep 28 '22 02:09

Carlo


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.

like image 37
Vucko Avatar answered Sep 28 '22 01:09

Vucko