Java 1
Java 1
Scanner;
// Define questions,
options, and correct answers
String[] questions = {
"1. What is the capital
of France?\nA. Berlin\nB.
Madrid\nC. Paris\nD. Rome",
"2. Which planet is
known as the Red Planet?\nA.
Earth\nB. Mars\nC. Jupiter\nD.
Saturn",
"3. Who wrote 'Romeo
and Juliet'?\nA. Charles
Dickens\nB. Jane
Austen\nC. William
Shakespeare\nD. Mark Twain",
"4. What is the largest
ocean on Earth?\nA. Atlantic
Ocean\nB. Indian Ocean\nC.
Arctic Ocean\nD. Pacific
Ocean",
"5. What is the
chemical symbol for water?\
nA. H2O\nB. CO2\nC. O2\nD.
NaCl"
};
char[] correctAnswers =
{'C', 'B', 'C', 'D', 'A'};
int score = 0;
System.out.println(questions[i])
;
System.out.print("Enter
your
answer (A, B, C, or D): ");
char userAnswer =
scanner.next().toUpperCase().
charAt(0); // Read user input
and convert to uppercase
// Validate input
if (userAnswer < 'A' ||
userAnswer > 'D') {
System.out.println("Invalid
answer! Please enter A, B, C,
or D.");
i--; // Decrement i to
repeat the question
continue; // Skip to
the next iteration of the loop
}
// Compare user
answer with the correct answer
switch (userAnswer) {
case 'A':
case 'B':
case 'C':
case 'D':
if (userAnswer ==
correctAnswers[i]) {
System.out.println("Correct!");
score++; //
Increment score for correct
answer
} else {
System.out.println("Wrong! The
correct answer was " +
correctAnswers[i] + ".");
}
break;
}
}
Output Example: