I've been trying to create a program in Java that asks a question and then depending on the users's input displays one of the dialogs. For some reason, when I click the correct option, it gives me the "Incorrect. The correct answer is A." message, although it is supposed to say "Correct!". I suspect the mistake somewhere in the check() method (lines 25 to 34), however I am not that sure, as the code looks pretty simple and I can't really identify what is wrong and why the program doesn't work properly. Could anyone help?
import javax.swing.JOptionPane;
public class Quiz {
public static void main(String[] args) {
String question = "What color is the hair of Disney princess Jasmine?\n";
question += "A. Black\nB. White\nC. Green\nD. Blue\nE. Rainbow";
// ask(question);
check(question, "A");
}
static String ask(String question) {
while (true) {
String answer = JOptionPane.showInputDialog(question);
answer = answer.toUpperCase();
if (answer.equals("A")) {
return question.toUpperCase();
}
else if(!answer.equals("B") && !answer.equals("C") && !answer.equals("D") && !answer.equals("E")) {
JOptionPane.showMessageDialog(null,"Invalid answer. Please enter A, B, C, D, or E.");
}
}
}
static void check(String question, String correctAnswer) {
String answer = ask(question);
if (answer.equals(correctAnswer)) {
JOptionPane.showMessageDialog(null,"Correct!");
}
else {
JOptionPane.showMessageDialog(null, "Incorrect. The correct answer is A.");
}
}
}