lundi 26 juin 2017

Android Quiz If-Else Statements and Toasts

The java code is what I have so far in Android Studio, as part of a multiple choice quiz app I am developing.

I want to create a toast that is shown when a button is clicked. As of now I have the following code. Depending on whether the correct button is clicked (ie. the button String is equal to the String of the respective element in the array) a different toast should be displayed.

I am a novice developer (new to both Java and Android Studio), and the code looks fine to me, but unfortunately, whenever I try to click the button in the app, I get a runtime error and my app is forced to close. Debugging in Android Studio hasn't helped me either.

If you have any suggestions where I made a mistake, I would be very, very happy. Thank you in advance for your help.

    /**Array containing correct answers for user**/
    String[] correctAnswerForUser = new String[3];

    /**Initialising array elements of answers array*/
    correctAnswerForUser[0] = "A";
    correctAnswerForUser[1] = "C";
    correctAnswerForUser[2] = "blank";

    /**Loop through the correct answers**/
    for (int index = 0; index < correctAnswerForUser.length; index++) {
        String correctAnswer = correctAnswerForUser[index];

    }


}

/**Method that stores the String "A" when Button A is clicked.**/
public void submitAnswerA(String correctAnswer) {
    String buttonA = "A";


        /**Displays toast when button is clicked**/
        if (buttonA.matches(correctAnswer)){
            Toast.makeText(getApplicationContext(), "Correct Answer",Toast.LENGTH_LONG).show();
        }
        else{
            Toast.makeText(getApplicationContext(), "Incorrect Answer",Toast.LENGTH_LONG).show();
        }

}

Aucun commentaire:

Enregistrer un commentaire