Building Quiz App with Core Java

This tutorial will guide you through creating a Quiz application using Core Java. This version of the Quiz app will present users with questions, collect answers, calculate scores, and, importantly, provide explanations for the incorrect answers at the end of the quiz. It's an excellent project for reinforcing Java fundamentals and learning about object-oriented programming, handling collections, and more.

Project Overview

The project consists of three main components:
  • Question.java: Defines the structure of quiz questions, including the question text, options, correct answer, and an explanation for the correct answer.
  • QuizManager.java: Manages the quiz logic, including displaying questions, collecting answers, calculating the final score, and showing explanations for correct answers.
  • Main.java: The entry point of the application that starts the quiz.

Step 1: Defining the Question Class

First, we'll create the Question class. This class will store the details of each quiz question, including the options, the correct answer, and an explanation for the correct answer.
package net.javaguides.quiz;

import java.util.List;

public class Question {
    private String questionText;
    private List<String> options;
    private String correctAnswer;
    private String explanation;

    public Question(String questionText, List<String> options, String correctAnswer, String explanation) {
        this.questionText = questionText;
        this.options = options;
        this.correctAnswer = correctAnswer;
        this.explanation = explanation;
    }

    // Getters for the fields
    public String getQuestionText() {
        return questionText;
    }

    public List<String> getOptions() {
        return options;
    }

    public String getCorrectAnswer() {
        return correctAnswer;
    }

    public String getExplanation() {
        return explanation;
    }
}

Step 2: Creating the QuizManager Class 

Next, let's implement the QuizManager class. This class will manage the quiz by displaying questions, accepting user inputs as answers, calculating scores, and displaying explanations for the incorrect answers at the end.
package net.javaguides.quiz;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class QuizManager {
    private List<Question> questions = new ArrayList<>();
    private int score = 0;

    public QuizManager() {
        // Populate the quiz with questions
        questions.add(new Question("What is the size of byte variable?",
            List.of("8 bit", "16 bit", "32 bit", "64 bit"), "8 bit",
            "Explanation: The byte data type is an 8-bit signed two's complement integer."));

        questions.add(new Question("Which loop construct in Java is best suited when the number of iterations is known? ",
                List.of("for loop", "while loop", "do-while loop", "break statement "), "for loop",
                "Explanation: The for loop in Java is used when the number of iterations is known or can be determined beforehand."));


        questions.add(new Question("Which statement is used to exit a loop prematurely?",
                List.of("return statement", "continue statement", "break statement", "exit statement "), "break statement",
                "Explanation: The break statement in Java is used to exit a loop prematurely and continue with the execution of the code outside the loop. "));

        // Add more questions here
    }

    public void startQuiz() {
        Scanner scanner = new Scanner(System.in);
        List<String> explanations = new ArrayList<>();

        for (Question question : questions) {
            System.out.println(question.getQuestionText());
            int index = 1;
            for (String option : question.getOptions()) {
                System.out.println(index++ + ". " + option);
            }
            System.out.print("Enter your answer (number): ");
            int answerIndex = scanner.nextInt() - 1;

            if (question.getOptions().get(answerIndex).equals(question.getCorrectAnswer())) {
                score++;
            } else {
                explanations.add(question.getExplanation());
            }
        }

        System.out.println("Quiz finished! Your score is: " + score + "/" + questions.size());
        if (!explanations.isEmpty()) {
            System.out.println("\nLet's learn from the questions we missed:");
            explanations.forEach(System.out::println);
        }

        scanner.close();
    }
}

Step 3: Implementing the Main Class 

Finally, the Main class serves as the entry point to our application. It initializes the QuizManager and starts the quiz.
package net.javaguides.quiz;

public class Main {
    public static void main(String[] args) {
        QuizManager quizManager = new QuizManager();
        quizManager.startQuiz();
    }
}

Compiling and Running the Application 

Save each class in its own .java file within a directory named net/java-guides/quiz/

Compile the classes with javac net/javaguides/quiz/*.java from the parent directory. 

Run the application using java net.javaguides.quiz.Main

Here is the output of all the correct answers:
What is the size of byte variable?
1. 8 bit
2. 16 bit
3. 32 bit
4. 64 bit
Enter your answer (number): 1
Which loop construct in Java is best suited when the number of iterations is known?
1. for loop
2. while loop
3. do-while loop
4. break statement
Enter your answer (number): 1
Which statement is used to exit a loop prematurely?
1. return statement
2. continue statement
3. break statement
4. exit statement
Enter your answer (number): 3
Quiz finished! Your score is: 3/3

Here is the output of a few incorrect answers, and note the explanations for incorrect answers in the output:

What is the size of byte variable?
1. 8 bit
2. 16 bit
3. 32 bit
4. 64 bit
Enter your answer (number): 2
Which loop construct in Java is best suited when the number of iterations is known?
1. for loop
2. while loop
3. do-while loop
4. break statement
Enter your answer (number): 2
Which statement is used to exit a loop prematurely?
1. return statement
2. continue statement
3. break statement
4. exit statement
Enter your answer (number): 1
Quiz finished! Your score is: 0/3

Let's learn from the questions we missed:
Explanation: The byte data type is an 8-bit signed two's complement integer.
Explanation: The for loop in Java is used when the number of iterations is known or can be determined beforehand.
Explanation: The break statement in Java is used to exit a loop prematurely and continue with the execution of the code outside the loop.

Conclusion 

Congratulations! You've built an enhanced Quiz app that not only tests the users' Java knowledge but also provides valuable learning through explanations of correct answers. This application demonstrates key Java concepts, including class design and list manipulation. Feel free to expand the application by adding more questions, varying the quiz topics, or even implementing a graphical user interface (GUI). 

Happy coding!

Comments