1
\$\begingroup\$

I've recently used this block of code from a quiz app where I check an array for the correct answer that was received from the browser and sent to the mobile device/application.

private void setCorrectAnswer() {
    //iterates till it finds the string that is equal to qAnswer(Correct Answer) in answerArray
    for (int i = 0; i < allButton.length; i++) {
        if (questionAns.equals(answerArray[i])) {
            viewAnswer = allButton[i];
            Log.i(TAG_INFO, "Correct Answer: " + answerArray[i]);
            i = allButton.length;
        }
    }
}

Another method to set the participant's answer:

private void setParticipantAnswer(View v) {
    try {
        studentViewAnswer = (Button)v;
        studentAnswer = studentViewAnswer.getText().toString();
        //iterates till it finds the string that is equal to studentAnswer in answerArray
        for (int i=0; i < allButton.length; i++) {
            if (studentAnswer.equals(answerArray[i])) {
                studentViewAnswer = allButton[i];
                Log.i(TAG_INFO, "Student Answer: " + answerArray[i]);
                i = allButton.length;
            }
        }
    } catch (NullPointerException e) {
        studentAnswer = null;
    }
}

Both of these methods set the button color to red (i.e. wrong) / green (i.e. right), which is triggered by another method.

My problem with this code is that it returns null when the user doesn't have an answer and every time the browser sends the choices I have to reset the last answer to null again. I've already caught the null with a nullexception. Would there be any problem if I continue doing this? If so, what's the better approach to this?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.