mardi 15 septembre 2020

While loop nested if else java

I have a problem with my while loop. It needs to keep asking the question until the answer is correct. Can someone please advise?

public class QuizW
{
    public static void main(String[] args)
    {
        String question = "What is the capital of Australia? \n";
        question += "A. Sydney\n";
        question += "B. Melburne\n";
        question += "C. Perth\n";
        question += "D. Cannberra\n";
        question += "E. Brisbane\n";

        String answer = JOptionPane.showInputDialog(question);
        answer = answer.toUpperCase();
        int answerCorrect = 0;
        
        while (answerCorrect == 0)
        {
            if (answer.equals("D"))
            {
                JOptionPane.showMessageDialog(null, "Correct!");
                break;
            }
            else if (answer.equals("A") || answer.equals("B") || answer.equals("C") || answer.equals("E"))
            {
                JOptionPane.showMessageDialog(null, "Incorrect. Please try again.");
            }
            else
            {
                JOptionPane.showMessageDialog(null, "Invalid answer. Please enter A, B, C, D, or E.");
            }
            JOptionPane.showInputDialog(question);
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire