Skip to Content
Course content

224: Building a Simple Quiz Application

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Alright, let's actually build something. We've spent a lot of time on the theory of classes and lists, but it's time to put them together. I want to build a simple quiz application—nothing fancy, just a console app that asks a few questions and tells you your score at the end. I'll walk you through how I'd tackle this, including the mistakes I'll probably make along the way.

Modeling the Question

First off, I need a way to represent a single question. I could just use a bunch of arrays, but that's a nightmare to maintain. I'll create a Question class. I need the text of the question, the possible options, and the correct answer.

public class Question {
    String prompt;
    String answer;

    public Question(String prompt, String answer) {
        this.prompt = prompt;
        this.answer = answer;
    }
}

Wait, looking at this, it's a bit too simple. If I just have a prompt and an answer, the user has to guess the exact word. That's frustrating. I'll add an array of options so the user can just pick 'A', 'B', or 'C'. I'll update the class to handle that.

public class Question {
    String prompt;
    String[] options;
    char correctOption;

    public Question(String prompt, String[] options, char correctOption) {
        this.prompt = prompt;
        this.options = options;
        this.correctOption = correctOption;
    }
}

The String Comparison Trap

Now, let's try to run this. I'll create a list of questions and a loop to iterate through them. I'll use a Scanner to get the user's input. Here is my first attempt at the logic inside the loop:

Scanner scanner = new Scanner(System.in);
int score = 0;

for (Question q : quizBank) {
    System.out.println(q.prompt);
    for (int i = 0; i < q.options.length; i++) {
        System.out.println((i + 1) + ": " + q.options[i]);
    }
    
    String userInput = scanner.next();
    if (userInput == "A") { // Let's assume I'm checking for a specific letter
        score++;
    }
}

I ran this, and it failed. Even when I typed 'A', the score didn't go up. Why? Right—I did the classic Java rookie mistake: using == to compare strings. In Java, == checks if the two objects are the same memory reference, not if their content is the same. I need to use .equals() or, even better, since I'm using char for the correct option, I should just read the input as a character.

Let's fix that and make it case-insensitive so the user doesn't get penalized for hitting the shift key.

char userInput = scanner.next().toUpperCase().charAt(0);
if (userInput == q.correctOption) {
    System.out.println("Correct!");
    score++;
} else {
    System.out.println("Wrong. The answer was " + q.correctOption);
}

Tying it all together

Now that the logic is solid, I don't want my main method to be a giant wall of code. It's cleaner to move the quiz execution into its own method or class. I'll create a QuizEngine class that takes a list of questions and handles the scoring. This makes the code reusable; if I want to add a "Science Quiz" and a "History Quiz" later, I don't have to rewrite the loop.

Here is how the final structure looks in my head: a Question POJO (Plain Old Java Object), a QuizEngine to handle the loop, and a Main class to define the specific questions and start the engine.

import java.util.*;

class Question {
    String prompt;
    String[] options;
    char correctOption;

    public Question(String prompt, String[] options, char correctOption) {
        this.prompt = prompt;
        this.options = options;
        this.correctOption = correctOption;
    }
}

class QuizEngine {
    public int runQuiz(List<Question> questions) {
        Scanner scanner = new Scanner(System.in);
        int score = 0;

        for (Question q : questions) {
            System.out.println("\n" + q.prompt);
            char label = 'A';
            for (String option : q.options) {
                System.out.println(label + ") " + option);
                label++;
            }
            System.out.print("Your answer: ");
            char input = scanner.next().toUpperCase().charAt(0);

            if (input == q.correctOption) {
                System.out.println("Nice!");
                score++;
            } else {
                System.out.println("Nope, it was " + q.correctOption);
            }
        }
        return score;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Question> javaQuiz = new ArrayList<>();
        javaQuiz.add(new Question("Which keyword is used to create a class?", 
            new String[]{"class", "struct", "object", "new"}, 'A'));
        javaQuiz.add(new Question("What is the default value of a boolean?", 
            new String[]{"true", "false", "null", "0"}, 'B'));

        QuizEngine engine = new QuizEngine();
        int finalScore = engine.runQuiz(javaQuiz);
        System.out.println("\nYour final score: " + finalScore + "/" + javaQuiz.size());
    }
}

Notice how I used a char label = 'A' inside the loop. By incrementing a character, Java automatically moves to 'B', 'C', and so on. It's a neat little trick to avoid manually typing out letters for every option.




📋 Practical Task

Build a Space Exploration Trivia Engine

Your task is to expand upon the Quiz Application. Instead of a Java quiz, build a "Space Exploration Trivia Engine" with the following specific requirements:

  • Create at least five Question objects related to astronomy or space flight.
  • Modify the QuizEngine so that it tracks not just the total score, but also which specific questions the user got wrong.
  • At the end of the quiz, print a "Review Sheet" that lists only the questions the user missed, showing the correct answer for each.
  • Implement a simple input validation check: if the user enters a character that isn't one of the provided options (e.g., they type 'Z' when only 'A', 'B', 'C', 'D' exist), the program should tell them "Invalid Option" and ask for the answer to that same question again.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.