Here's a simple Java quiz program that asks two true/false questions, stores the user's answers as booleans, and then prints out both the user's answers and the correct answers at the end:
import java.util.Scanner;
public class QuizProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Declare the questions and answers
String question1 = "Is the sky blue?";
boolean answer1Correct = true; // Correct answer is true
String question2 = "Is 2 + 2 equal to 5?";
boolean answer2Correct = false; // Correct answer is false
// Ask the first question
System.out.println(question1);
boolean userAnswer1 = getUserAnswer(scanner);
// Ask the second question
System.out.println(question2);
boolean userAnswer2 = getUserAnswer(scanner);
// Print results
System.out.println("\nYour Answers:");
System.out.println("1. " + question1 + " Your answer: " + userAnswer1 + " | Correct answer: " + answer1Correct);
System.out.println("2. " + question2 + " Your answer: " + userAnswer2 + " | Correct answer: " + answer2Correct);
scanner.close();
}
private static boolean getUserAnswer(Scanner scanner) {
String input = scanner.nextLine();
// Convert user input to lowercase for case-insensitive comparison
return input.equalsIgnoreCase("true");
}
}
How It Works:
- Question Definitions: The program defines two questions and their correct answers.
- User Input: It prompts the user for answers, expecting "true" or "false".
- Input Processing: The
getUserAnswer
method reads the user input and converts it to a boolean based on whether the input matches "true" (case insensitive). - Result Display: After both questions are answered, the program prints out the user's answers alongside the correct answers.
Running the Program:
- Compile the program using
javac QuizProgram.java
. - Execute it with
java QuizProgram
. - Follow the prompts to answer the questions.
This program provides a simple framework for a true/false quiz and can be easily expanded with more questions as needed.