



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




import java.util.Scanner; public class Quiz { public static void main(String[] args) { // Initialize Scanner object for user input Scanner scanner = new Scanner(System.in); // Define quiz questions and answers String[] questions = { "1. Who directed the film “Inception” (2010)?", "2. What sport is associated with the term “slam dunk”?", "3. Which legendary musician is known as the “King of Pop”?", "4. Who is the youngest player to ever score in a World Cup tournament?", "5. Which player holds the record for the most goals scored in a single Premier League season?" }; String[][] options = { {"A. Quentin Tarantino", "B. Steven Spielberg", "C. Christopher Nolan", "D. Martin Scorsese"}, {"A. Basketball", "B. Tennis", "C. Soccer", "D. Golf"}, {"A. Elvis Presley", "B. Freddie Mercury", "C. Bob Dylan", "D. Michael Jackson"}, {"A. Lionel Messi", "B. Pelé", "C. Kylian Mbappé", "D. Diego Maradona"}, {"A. Erling Haaland", "B. MCristiano Ronaldo", "C. Thierry Henry", "D. Alan Shearer"} }; char[] answers = {'C', 'A', 'D', 'B', 'A'}; // Correct answers for each question // Display instructions System.out.println("Welcome to the Quiz Game!"); System.out.println("Please enter the letter corresponding to the correct answer \n (A, B, C, or D).\n"); int score = 0; // Initialize score counter // Iterate through each question for (int i = 0; i < questions.length; i++) { // Display question and options System.out.println(questions[i]); for (String option : options[i]) { System.out.println(option); }
// Prompt user for answer System.out.print("Choose your answer: "); char userAnswer = scanner.next().toUpperCase().charAt(0); // Convert input to uppercase and get first character // Validate user input if (userAnswer < 'A' || userAnswer > 'D') { System.out.println("Invalid input. Please enter A, B, C, or D."); i--; // Decrement i to repeat the same question continue; } // Compare user answer with correct answer if (userAnswer == answers[i]) { System.out.println("Correct!"); score++; // Increment score for correct answer } else { System.out.println("Incorrect!"); System.out.println("Correct Answer is " + answers[i]); } } // Calculate and display final score double percentage = (double) score / questions.length * 100; if (score > 0) { System.out.println("\nYou got " + score + " correct answers out of " + questions.length + " questions"); System.out.printf("Your Score: %.2f%%\n", percentage); } else { System.out.println("\nYou got " + score + " correct answer out of "