Sure! Below is a simple Java program that implements a true/false quiz with two questions. The program stores the user's answers as booleans and prints out both the user's answers and the correct answers at the end.
import java.util.Scanner;
public class Quiz {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Questions and corresponding correct answers
String question1 = "Java is an object-oriented programming language, true or false?";
boolean correctAnswer1 = true;
String question2 = "There are only 2 possible values which can be held by a boolean variable, true or false?";
boolean correctAnswer2 = true;
// Ask the first question
System.out.println(question1);
boolean userAnswer1 = getBooleanAnswer(scanner);
// Ask the second question
System.out.println(question2);
boolean userAnswer2 = getBooleanAnswer(scanner);
// Print user's answers and correct answers
System.out.println("Question 1 - Your answer: " + userAnswer1 + ". Correct answer: " + correctAnswer1);
System.out.println("Question 2 - Your answer: " + userAnswer2 + ". Correct answer: " + correctAnswer2);
scanner.close();
}
// Helper method to get boolean answer from user
private static boolean getBooleanAnswer(Scanner scanner) {
String input = scanner.nextLine().trim().toLowerCase();
// Interpret the user's input as a boolean
if ("true".equals(input)) {
return true;
} else if ("false".equals(input)) {
return false;
} else {
System.out.println("Invalid input! Please enter true or false.");
return getBooleanAnswer(scanner); // Recursively ask again if the input is invalid
}
}
}
Explanation
- Question Declaration: The questions are stored in string variables along with their correct boolean answers.
- User Input: The program prompts the user for their answers, reads the input, and converts it to a boolean value.
- Validation: The
getBooleanAnswer
method ensures that the user inputs either "true" or "false". If the input is invalid, it prompts the user again. - Output: At the end of the quiz, the program prints out the user's answers along with the correct ones.
You can compile and run the program to see how it works!