Write a short quiz program which asks two true/false questions and stores the user's answers as booleans. At the end of the program it should print the user's answers with the correct answers.

Note: you should use the same quiz questions and correct answers as the sample run below.

Sample run:

Java is an object-oriented programming language, true or false?
true
There are only 2 possible values which can be held by a boolean variable, true or false?
false

Question 1 - Your answer: true. Correct answer: true
Question 2 - Your answer: false. Correct answer: true
in java using the nextBoolean method

1 answer

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

  1. Make sure you have Java installed on your machine.
  2. Copy and paste the above code into a text file, and save it as QuizProgram.java.
  3. Open a terminal or command prompt.
  4. Navigate to the directory where you saved the file.
  5. Compile the program with the command:
    javac QuizProgram.java
    
  6. Run the compiled program with the command:
    java QuizProgram
    
  7. Follow the prompts to answer the questions with true or false.

Note

  • The program uses the nextBoolean() method of the Scanner class to read boolean inputs directly.
  • Ensure to enter true or false exactly (case-sensitive) as strings while running since nextBoolean() expects a boolean input.