Certainly! Below is a simple Java program that implements a short quiz, asking two true/false questions, capturing the user's answers as booleans, and displaying 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);
// Define questions and correct answers
String question1 = "Java is an object-oriented programming language, true or false?";
String question2 = "There are only 2 possible values which can be held by a boolean variable, true or false?";
boolean correctAnswer1 = true;
boolean correctAnswer2 = false;
// Store user answers
boolean userAnswer1, userAnswer2;
// Ask the first question
System.out.println(question1);
userAnswer1 = scanner.nextBoolean();
// Ask the second question
System.out.println(question2);
userAnswer2 = scanner.nextBoolean();
// Display the results
System.out.println("\nQuestion 1 - Your answer: " + userAnswer1 + ". Correct answer: " + correctAnswer1);
System.out.println("Question 2 - Your answer: " + userAnswer2 + ". Correct answer: " + correctAnswer2);
// Close the scanner
scanner.close();
}
}
How to Run This Program
- Make sure you have Java installed on your machine.
- Copy and paste the above code into a text file, and save it as
QuizProgram.java
. - Open a terminal or command prompt.
- Navigate to the directory where you saved the file.
- Compile the program with the command:
javac QuizProgram.java
- Run the compiled program with the command:
java QuizProgram
- Follow the prompts to answer the questions with
true
orfalse
.
Note
- The program uses the
nextBoolean()
method of theScanner
class to read boolean inputs directly. - Ensure to enter
true
orfalse
exactly (case-sensitive) as strings while running sincenextBoolean()
expects a boolean input.