Build a Java Quiz System

Build a console quiz game using Java OOP: classes, arrays, and methods.

Introduction

30 Second Summary

Think about every quiz you have taken online. Someone had to write the code that stores the questions, checks your answers, tracks your score, and tells you how you did at the end.

In this project, you will build an interactive console quiz game in Java that asks multiple-choice questions, validates your input, and grades your performance using clean object-oriented code.

What You'll Build

You run the program and an interactive quiz launches right in your terminal, presenting questions one by one, giving instant correct-or-wrong feedback after each answer, and revealing your final score and grade when you finish.

By the end of this project, you'll have:

  • A working quiz game you can run in your terminal that asks 5 questions, gives instant feedback on each answer, and displays your percentage score alongside a letter grade.
  • Bullet-proof input validation that handles anything a user types without crashing, politely re-prompting until they enter a valid answer.
  • Three connected Java classes that separate your data, game logic, and startup code, mirroring how professional applications are structured.
  • Secret Mission: Add difficulty levels so the player can choose Easy, Medium, or Hard questions before playing.

Are there any prerequisites?

You should be comfortable with basic Java concepts like variables, if/else statements, methods, and loops. No prior knowledge of arrays or OOP is required.

Before We Start

Before we dive in, let's lock in what you're about to build and why it matters.

You're going to build a complete interactive quiz game in Java, and along the way you'll learn arrays, classes, and modern Java features like switch expressions.

Set Up Your Java Project

Before you can write any quiz logic, you need a properly configured project in Eclipse. Eclipse needs to know which version of Java to compile against, and where to put your source files.

In this step, you'll create a new project, add your first class, and run a test message. Seeing output in the console proves your entire toolchain works before you start building the quiz.

In this step, get ready to:
  • Create a new Java project named JavaQuizSystem configured for Java 21.
  • Create a QuizApp class with a main method.
  • Run the program and confirm it prints to the console.
Create a new Java project in Eclipse

Eclipse organizes code into projects. Each project has its own settings, including which Java version to use for compiling and running.

  • In Eclipse, click File in the top menu bar.
  • Click New, then select Java Project.
  • In the Project name field, type JavaQuizSystem.
  • Under JRE, confirm that JavaSE-21 is selected. If it shows a different version, select Use a project specific JRE and choose Java 21 from the dropdown.
  • Click Finish.

Your new JavaQuizSystem project appears in the Package Explorer panel on the left. You should see a src folder inside it.

Don't see Java 21 in the JRE dropdown?

Go to Window > Preferences > Java > Installed JREs. Click Add and browse to your Java 21 JDK installation folder. Once added, check the box next to it to make it the default.

Help me configure Java 21 in Eclipse

Create the QuizApp class

Every Java program needs a class with a main method. This is the entry point that runs when you execute the program.

  • In the Package Explorer, right-click the src folder inside JavaQuizSystem.
  • Select New, then click Class.
  • In the Name field, type QuizApp.
  • Under Which method stubs would you like to create?, check the box for public static void main(String[] args).
  • Click Finish.

Eclipse creates QuizApp.java and opens it in the editor. You should see a class with an empty main method and a // TODO Auto-generated method stub comment inside it.

Add a test message and run the program

Now you'll replace the placeholder comment with a real print statement and run the program to confirm everything is connected.

  • In the editor, delete the // TODO Auto-generated method stub comment inside the main method.
  • Replace it with the following code so your file looks like this:
public class QuizApp {
    public static void main(String[] args) {
        // Print a test message to prove the project runs
        System.out.println("Hello Quiz! Let's test your Java knowledge.");
    }
}

What does this code do?

System.out.println() prints text to the console and adds a new line at the end. This is how Java programs display output to the user.

The main method is where Java starts executing your program. Everything inside its curly braces runs when you click Run.

  • Save the file by pressing Ctrl+S.

Before you run this, what do you expect to see in the console?

  • Right-click anywhere in the QuizApp.java editor.
  • Select Run As, then click Java Application.

The Console panel at the bottom of Eclipse displays: Hello Quiz! Let's test your Java knowledge.

Don't see any output in the console?

Make sure you saved the file (Ctrl+S) before running. Eclipse runs the last saved version, not what's currently in the editor.

Check that your println line ends with a semicolon and that the string is wrapped in double quotes. A missing semicolon causes a red error marker on the line.

Help me fix my QuizApp not printing to the console

✔️ Awesome, I've got everything!

Great. Double check you've saved your file before moving on.

ⓧ I'd like to double check the full code

Here is the complete QuizApp.java file at this point. Make sure yours matches exactly.

public class QuizApp {
    public static void main(String[] args) {
        System.out.println("Hello Quiz! Let's test your Java knowledge.");
    }
}

Your environment is ready and proven. Next up, you'll build a working quiz with real questions and answers.

Build a Hardcoded 2-Question Quiz

Your project is set up and printing to the console. Now it is time to turn that empty shell into a real, playable quiz.

In this step, you will build a working 2-question quiz using only individual variables, print statements, and if/else blocks. The quiz will work perfectly. But pay attention to how the code looks by the end.

In this step, get ready to:
  • Add a Scanner to read user input and a variable to track the score.
  • Write the code for 2 complete quiz questions with answer checking.
  • Display the final score at the end of the quiz.
Add a Scanner and build the first question

A quiz needs to read what the player types. Java's Scanner class connects your program to keyboard input so you can capture answers.

  • Open QuizApp.java in the Eclipse editor.
  • Select all the existing code and replace it with the following:
import java.util.Scanner;

public class QuizApp {
    public static void main(String[] args) {
        // Create a Scanner to read keyboard input
        Scanner scanner = new Scanner(System.in);
        int score = 0;

        // Question 1
        System.out.println("\nQuestion 1: What is the correct way to declare a variable in Java?");
        System.out.println("  1. variable x = 5;");
        System.out.println("  2. int x = 5;");
        System.out.println("  3. x = 5 int;");
        System.out.println("  4. declare x = 5;");
        System.out.print("Your answer: ");
        int answer1 = scanner.nextInt();
        if (answer1 == 2) {
            System.out.println("Correct!");
            score++;
        } else {
            System.out.println("Wrong! The correct answer was: int x = 5;");
        }
    }
}

What does this code do?

  • import java.util.Scanner; loads the Scanner class so your program can read keyboard input.
  • scanner.nextInt() waits for the player to type a number and press Enter, then stores it in answer1.
  • The if/else block checks whether the answer matches the correct choice (option 2). If it does, score++ adds one point.
  • Save QuizApp.java by pressing Ctrl+S.
  • Right-click inside the editor, select Run As, then click Java Application.
  • In the Console panel at the bottom, type 2 and press Enter.

You should see the question printed with 4 options, and after answering, the console prints "Correct!" because option 2 is the right answer.

Seeing a red error in the console?

  • If you see Scanner cannot be resolved to a type, make sure the import java.util.Scanner; line is at the very top of the file, above the class declaration.
  • If the program hangs without printing anything, check that you used System.out.println (not System.out.print) for the question text so it appears before the input prompt.

Help me debug my Scanner error in QuizApp.java

Add the second question and display the score

One question works. Now add a second question using the same pattern, plus a line at the end that shows the player's total score.

  • In QuizApp.java, find the closing brace of the Question 1 if/else block (the } after the "Wrong!" line).
  • Add the following code below it, before the closing braces of the method and class:
        // Question 2
        System.out.println("\nQuestion 2: Which keyword is used to create a new object in Java?");
        System.out.println("  1. create");
        System.out.println("  2. object");
        System.out.println("  3. new");
        System.out.println("  4. make");
        System.out.print("Your answer: ");
        int answer2 = scanner.nextInt();
        if (answer2 == 3) {
            System.out.println("Correct!");
            score++;
        } else {
            System.out.println("Wrong! The correct answer was: new");
        }

        System.out.println("\nYou got " + score + " out of 2 correct!");

What does this code do?

  • Question 2 follows the exact same structure as Question 1: print the question, print 4 options, read an integer, check with if/else, update score.
  • The final println uses string concatenation (+) to insert the score variable into the output message.
  • Save QuizApp.java by pressing Ctrl+S.

Before you run this, think about what will happen. Will you see both questions one after another, or all at once?

  • Right-click inside the editor, select Run As, then click Java Application.
  • Answer both questions by typing a number and pressing Enter for each.

Each question appears one at a time. The program waits for your answer before showing the next one. At the end you see "You got X out of 2 correct!" with your actual score.

Notice the repetition?

Scroll through your code. The block for Question 1 and the block for Question 2 are almost identical. The same 8-line pattern is copy-pasted with different text.

Imagine adding 5 more questions. You would copy that same block 5 more times. If you wanted to change the answer format, you would need to edit every single block. This is the exact problem that arrays and loops solve in the next step.

Program crashes when you type an answer?

  • If you typed a letter instead of a number, the program crashes with an error. That is expected for now. Input validation comes in a later step.
  • If only one question appears and the program ends, check that your Question 2 code is inside the main method (between the method's opening and closing braces).

Help me figure out why my quiz is not showing both questions

✔️ Awesome, I've got everything!

Great. Double check you have saved your file before moving on.

ⓧ I'd like to double check the full code

Your QuizApp.java should contain these sections in order. Scroll up and confirm each one is present:

  • The import java.util.Scanner; line at the very top.
  • Inside main: the Scanner and score variable declarations.
  • The Question 1 block: println statements, scanner.nextInt(), and if (answer1 == 2) check.
  • The Question 2 block: same structure with if (answer2 == 3) check.
  • The final score line: "You got " + score + " out of 2 correct!".

Your quiz works. But your code is already straining under the weight of just 2 questions. Next up, you will use arrays and a loop to handle 5 questions with less code than you wrote for 2.

Refactor to Arrays and Loops

In the last step, you built a working 2-question quiz. But look at how much code it took. Each question needed its own block of nearly identical print, read, and check logic.

Adding 5 more questions would mean copy-pasting that same block 5 more times. Arrays let you store all your questions in one structure, and a for loop processes every single question with zero repeated code.

In this step, get ready to:
  • Store all questions, options, and answers in arrays.
  • Replace duplicated code blocks with a single for loop.
  • Expand from 2 to 5 questions without adding any new logic.
Replace hardcoded questions with arrays

An array is a container that holds multiple values under one variable name. Instead of separate variables for each question, you store all questions in one array, all options in another, and all correct answers in a third.

  • In QuizApp.java, select and delete everything from the // Question 1 comment down to and including the line that says System.out.println("\nYou got " + score + " out of 2 correct!");.
  • In the empty space below int score = 0;, paste these three arrays:
        String[] questions = {
            "What is the correct way to declare a variable in Java?",
            "Which keyword is used to create a new object in Java?",
            "What does the 'void' keyword mean in a method declaration?",
            "Which of these is a valid Java array declaration?",
            "What is the output of: System.out.println(10 % 3);"
        };

        String[][] options = {
            {"variable x = 5;", "int x = 5;", "x = 5 int;", "declare x = 5;"},
            {"create", "object", "new", "make"},
            {"The method returns an integer", "The method returns nothing", "The method is empty", "The method is private"},
            {"int arr[] = new int[5];", "int arr = new int[5];", "array int arr = new[5];", "int[5] arr = new int;"},
            {"3", "0", "1", "3.33"}
        };

        int[] correctAnswers = {1, 2, 1, 0, 2};

What does this code do?

  • questions is a String[] array holding all 5 question texts. Each element is one question.
  • options is a String[][] (2D array). Each row holds the 4 answer choices for one question.
  • correctAnswers is an int[] array storing the index (starting from 0) of the correct option for each question.

Notice you now have 5 questions but wrote zero extra logic. Adding questions is just adding entries to the arrays.

What is a 2D array?

A 2D array is an array of arrays. Think of it like a spreadsheet: each row is one question's set of options, and each column is one option within that row.

options[0] gives you the entire first row (all 4 options for question 1). options[0][1] gives you the second option of the first question.

Add a for loop to process all questions

The arrays hold the data, but nothing displays or checks answers yet. A single for loop replaces all the duplicated logic you deleted.

  • Below the correctAnswers array, add this for loop and final score output:
        for (int i = 0; i < questions.length; i++) {
            System.out.println("\nQuestion " + (i + 1) + ": " + questions[i]);
            for (int j = 0; j < options[i].length; j++) {
                System.out.println("  " + (j + 1) + ". " + options[i][j]);
            }
            System.out.print("Your answer: ");
            int answer = scanner.nextInt();
            if (answer - 1 == correctAnswers[i]) {
                System.out.println("Correct!");
                score++;
            } else {
                System.out.println("Wrong! The correct answer was: " + options[i][correctAnswers[i]]);
            }
        }

        System.out.println("\nYou got " + score + " out of 5 correct!");

What does this code do?

  • The outer for loop walks through each question using index i. It runs once per question, no matter how many questions exist.
  • The inner for loop (using j) prints each option for the current question. It reads from options[i], which is the row of options for question i.
  • answer - 1 == correctAnswers[i] converts the user's 1-based choice (typing 1-4) to a 0-based index to match the array.
  • The wrong-answer message uses options[i][correctAnswers[i]] to look up and display the correct answer text automatically.
  • Save QuizApp.java by pressing Ctrl+S.

Seeing red underlines in Eclipse?

  • Make sure you deleted ALL of the old question blocks. If any leftover variables like answer1 or answer2 remain, they will conflict with the new code.
  • Check that your arrays are placed between the int score = 0; line and the for loop. The for loop needs the arrays to exist above it.
  • Verify your curly braces match. Each array uses { } for its contents, and the 2D array has nested { } for each row.

Why is Eclipse showing red underlines in my refactored quiz code?

Run the refactored quiz

Your code now handles 5 questions with fewer lines than the old 2-question version used. Before you run it, think about what you expect to see.

  • How many questions do you think will appear? Will the scoring still work correctly for all 5?
  • Right-click QuizApp.java in the Package Explorer.
  • Select Run As, then Java Application.

All 5 questions appear one after another. Answer each one, and at the end you see your final score printed as You got X out of 5 correct!.

Count the lines in your file. The code that handles all 5 questions is shorter than the old code that handled just 2. That is the power of arrays and loops working together.

Only seeing 1 or 2 questions?

  • Check that your questions array has exactly 5 entries separated by commas. A missing comma between entries causes a compilation error, but a missing entry means fewer questions.
  • Verify all three arrays have the same number of entries: 5 questions, 5 rows in options, and 5 values in correctAnswers. Mismatched lengths cause an ArrayIndexOutOfBoundsException at runtime.

Why is my Java quiz not showing all 5 questions?

Why are the arrays a hidden problem?

Your three arrays are parallel. Question 0's text is in questions[0], its options are in options[0], and its correct answer is in correctAnswers[0]. They only work because YOU keep them in sync.

If you accidentally reorder one array without reordering the others, questions get matched to wrong options or wrong answers. Nothing warns you. In the next step, you will solve this by bundling each question's data into a single object.

✔️ Awesome, I've got everything!

Great. Double check you have saved your file before moving on.

ⓧ I'd like to double check the full code

Here is the complete QuizApp.java at this point. Make sure yours matches:

import java.util.Scanner;

public class QuizApp {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int score = 0;

        String[] questions = {
            "What is the correct way to declare a variable in Java?",
            "Which keyword is used to create a new object in Java?",
            "What does the 'void' keyword mean in a method declaration?",
            "Which of these is a valid Java array declaration?",
            "What is the output of: System.out.println(10 % 3);"
        };
        String[][] options = {
            {"variable x = 5;", "int x = 5;", "x = 5 int;", "declare x = 5;"},
            {"create", "object", "new", "make"},
            {"The method returns an integer", "The method returns nothing", "The method is empty", "The method is private"},
            {"int arr[] = new int[5];", "int arr = new int[5];", "array int arr = new[5];", "int[5] arr = new int;"},
            {"3", "0", "1", "3.33"}
        };

        int[] correctAnswers = {1, 2, 1, 0, 2};

        for (int i = 0; i < questions.length; i++) {
            System.out.println("\nQuestion " + (i + 1) + ": " + questions[i]);
            for (int j = 0; j < options[i].length; j++) {
                System.out.println("  " + (j + 1) + ". " + options[i][j]);
            }
            System.out.print("Your answer: ");
            int answer = scanner.nextInt();
            if (answer - 1 == correctAnswers[i]) {
                System.out.println("Correct!");
                score++;
            } else {
                System.out.println("Wrong! The correct answer was: " + options[i][correctAnswers[i]]);
            }
        }

        System.out.println("\nYou got " + score + " out of 5 correct!");
    }
}

Your quiz handles 5 questions with cleaner, shorter code than the old 2-question version. But those three parallel arrays are fragile. Next up, you will bundle each question's data into a single object so nothing can fall out of sync.

Create the Question Class

Your quiz works, but take a closer look at how the data is organized. You have three separate arrays: questions, options, and correctAnswers.

These arrays are connected only by position. If you accidentally reorder one array without updating the others, your quiz silently gives wrong answers with no error to warn you. A class bundles related data together so each question becomes one self-contained object that carries its own text, options, and correct answer.

In this step, get ready to:
  • Create a new Question.java class with private fields and a constructor.
  • Add getter methods and behavior methods to the class.
  • Update QuizApp.java to use Question objects instead of parallel arrays.
Create the Question class with private fields

The Question class will hold everything about a single quiz question in one place. You will start with the fields and the constructor that initializes them.

  • In the Package Explorer on the left side of Eclipse, right-click your JavaQuizSystem project (or its src folder).
  • Select New then Class.
  • In the Name field, type Question.
  • Make sure no method stubs are checked (uncheck public static void main if it is selected).
  • Click Finish.

Eclipse creates Question.java and opens it in the editor with an empty class body.

  • Delete the auto-generated content and replace it with the following code that defines the class structure:
public class Question {
    // Each question stores its own text, options, and correct answer
    private String questionText;
    private String[] options;
    private int correctAnswerIndex;

    // Constructor takes all three values when creating a Question
    public Question(String questionText, String[] options, int correctAnswerIndex) {
        this.questionText = questionText;
        this.options = options;
        this.correctAnswerIndex = correctAnswerIndex;
    }
}

What does this code do?

The three private fields store the question's data. Making them private means no other class can change them directly. This is called encapsulation.

The constructor is a special method that runs when you create a new Question object. The this keyword distinguishes the object's field from the parameter with the same name.

  • Save the file with Ctrl+S.
  • Check that no red underlines appear in the editor. A clean file means Eclipse compiled your class successfully.

Seeing red underlines?

  • Make sure the class name Question matches the filename Question.java exactly (capital Q).
  • Check that every opening brace { has a matching closing brace }.
  • Confirm you have a semicolon at the end of each field declaration.

Why isn't my Question class compiling in Eclipse?

Add getter and behavior methods

With the fields locked behind private, other classes need getter methods to read the data. You will also add two behavior methods that give the Question class the ability to check answers and display itself.

  • In Question.java, place your cursor after the closing brace of the constructor but before the final closing brace of the class.
  • Add the following methods below the constructor:
    public String getQuestionText() {
        return questionText;
    }

    public String[] getOptions() {
        return options;
    }

    public int getCorrectAnswerIndex() {
        return correctAnswerIndex;
    }

    // Returns the actual text of the correct answer
    public String getCorrectAnswer() {
        return options[correctAnswerIndex];
    }

    // Checks if the user's answer matches the correct index
    public boolean isCorrect(int userAnswer) {
        return userAnswer == correctAnswerIndex;
    }

    // Prints the question and all its options
    public void display(int questionNumber) {
        System.out.println("\nQuestion " + questionNumber + ": " + questionText);
        for (int i = 0; i < options.length; i++) {
            System.out.println("  " + (i + 1) + ". " + options[i]);
        }
    }

What do these methods do?

  • getQuestionText(), getOptions(), and getCorrectAnswerIndex() are standard getters that let other classes read the private fields.
  • getCorrectAnswer() looks up the actual answer text using the index. This is more useful than just returning a number.
  • isCorrect(int userAnswer) compares the user's choice against the correct index and returns true or false.
  • display(int questionNumber) prints the question and loops through the options array to show numbered choices. This means the Question knows how to present itself.
  • Save Question.java with Ctrl+S.
  • Confirm no red underlines appear anywhere in the file.

Red underlines on the new methods?

  • Make sure the methods are inside the class braces but outside the constructor braces.
  • Check that display uses options.length (not options.size()). Arrays use .length, not .size().

Why are my methods causing errors in Question.java?

✔️ Awesome, I've got everything!

Great. Make sure you have saved Question.java with no errors before moving on.

ⓧ I'd like to double check the full code

Scroll up and confirm your Question.java file contains, in this order:

  • The class declaration with three private fields (questionText, options, correctAnswerIndex).
  • The constructor that takes all three values and assigns them with this.
  • Four getter methods: getQuestionText(), getOptions(), getCorrectAnswerIndex(), getCorrectAnswer().
  • The isCorrect(int userAnswer) method returning a boolean.
  • The display(int questionNumber) method that prints the question and numbered options.
Update QuizApp to use Question objects

Now you will replace the three disconnected arrays in QuizApp.java with an array of Question objects. Each question will carry its own text, options, and correct answer together.

  • Switch to the QuizApp.java tab in the editor.
  • Find and delete the three array declarations (the String[] questions block, the String[][] options block, and the int[] correctAnswers line).
  • In their place, add the following code that creates Question objects:
        Question[] questions = new Question[5];

        questions[0] = new Question(
            "What is the correct way to declare a variable in Java?",
            new String[]{"variable x = 5;", "int x = 5;", "x = 5 int;", "declare x = 5;"},
            1
        );
        questions[1] = new Question(
            "Which keyword is used to create a new object in Java?",
            new String[]{"create", "object", "new", "make"},
            2
        );
        questions[2] = new Question(
            "What does the 'void' keyword mean in a method declaration?",
            new String[]{"The method returns an integer", "The method returns nothing", "The method is empty", "The method is private"},
            1
        );
        questions[3] = new Question(
            "Which of these is a valid Java array declaration?",
            new String[]{"int arr[] = new int[5];", "int arr = new int[5];", "array int arr = new[5];", "int[5] arr = new int;"},
            0
        );
        questions[4] = new Question(
            "What is the output of: System.out.println(10 % 3);",
            new String[]{"3", "0", "1", "3.33"},
            2
        );

What changed here?

Instead of three separate arrays, you now have a single Question[] array. Each new Question(...) call bundles the question text, its options, and the correct answer index into one object.

If you reorder questions[0] and questions[1], the options and correct answer travel with the question automatically. No more silent mismatches.

You will see red underlines in the for loop below because it still references the old array variables. That is expected.

  • Now delete the entire existing for loop (from for (int i = 0; down to its closing brace).
  • Replace it with this loop that uses the Question object methods:
        for (int i = 0; i < questions.length; i++) {
            // Let the Question display itself
            questions[i].display(i + 1);
            System.out.print("Your answer: ");
            int answer = scanner.nextInt();
            // Use isCorrect() to check the answer
            if (questions[i].isCorrect(answer - 1)) {
                System.out.println("Correct!");
                score++;
            } else {
                System.out.println("Wrong! The correct answer was: " + questions[i].getCorrectAnswer());
            }
        }

        System.out.println("\nYou got " + score + " out of 5 correct!");

What does this loop do differently?

  • questions[i].display(i + 1) asks the Question object to print itself. The loop no longer needs to know how to format output.
  • questions[i].isCorrect(answer - 1) delegates answer-checking to the object. The loop no longer needs to look up a separate array.
  • questions[i].getCorrectAnswer() retrieves the text of the correct answer directly from the object.
  • Save QuizApp.java with Ctrl+S.
  • Confirm all red underlines are gone from both files.

Before you run the program, what do you expect to see differently from the last step?

  • Right-click QuizApp.java in the Package Explorer and select Run As then Java Application.

The quiz behaves identically to before. You still see 5 questions, answer each one, get feedback, and see your final score. The difference is entirely in how the code is organized.

Why does it look the same?

A refactor changes the structure of your code without changing what it does. The user experience is identical, but your code is now safer and easier to extend. Try swapping questions[0] and questions[1] in the array. Run again and notice the options and correct answers follow their question automatically.

Getting a compilation error when you run?

  • Make sure you deleted all three old arrays (String[] questions, String[][] options, int[] correctAnswers). Any leftover reference causes an error.
  • Check that the for loop uses questions[i].display(i + 1) and questions[i].isCorrect(answer - 1), not the old correctAnswers[i] syntax.
  • Verify that Question.java is in the same source folder as QuizApp.java. If they are in different packages, Eclipse cannot find the class.

Why is QuizApp.java not recognizing my Question class?

✔️ Awesome, I've got everything!

Great. Make sure you saved both files and the quiz runs with the same 5 questions and scoring as before.

ⓧ I'd like to double check the full code

Scroll up and confirm your QuizApp.java file contains, in this order:

  • The import java.util.Scanner; line at the top.
  • The main method starting with Scanner and score declarations.
  • A Question[] array of size 5 with each element created using new Question(...).
  • A for loop calling questions[i].display(i + 1), questions[i].isCorrect(answer - 1), and questions[i].getCorrectAnswer().
  • The final score print statement.

Your questions are now proper objects that bundle their data together. Next up, you will build a Quiz class that handles the game flow, adds input validation so the program never crashes, and grades performance with a modern switch expression.

Build the Quiz Class

Your Question class bundles data and behavior together beautifully. But look at QuizApp.java. The main method still handles everything: looping, scoring, reading input, and printing results.

A Quiz class separates game logic from data, mirroring how professional Java applications are built. This is also where you will add input validation (so the quiz never crashes on bad input) and a Java 21 switch expression for grading.

In this step, get ready to:
  • Create a Quiz class with fields, a constructor, and a welcome banner using a text block.
  • Add input validation that re-prompts instead of crashing on bad input.
  • Add a results display with a switch expression that grades performance.
Create Quiz.java with the game skeleton

The Quiz class owns the entire game flow: welcoming the player, asking questions, tracking the score, and showing results. It receives a Question[] array and handles everything else internally.

  • Right-click your JavaQuizSystem project's src folder in the Package Explorer.
  • Select New, then Class.
  • Enter Quiz as the class name and click Finish.
  • Replace the generated content with the following fields and constructor:
import java.util.Scanner;

public class Quiz {
    // The array of questions to ask
    private Question[] questions;
    // Tracks how many the player gets right
    private int score;
    // Total number of questions (for percentage calc)
    private int totalQuestions;
    // Reads player input from the console
    private Scanner scanner;

    public Quiz(Question[] questions) {
        this.questions = questions;
        this.totalQuestions = questions.length;
        this.score = 0;
        this.scanner = new Scanner(System.in);
    }
}

What does this code do?

The constructor receives the question array and derives totalQuestions from its length. It also creates a fresh Scanner for reading console input.

All four fields are private. Nothing outside the Quiz class can tamper with the score or swap the question list mid-game. This is encapsulation in action.

  • Now add the start() method inside the class, below the constructor's closing brace:
    public void start() {
        // Text block: multi-line string without clunky concatenation
        System.out.println("""
                ================================
                   WELCOME TO THE JAVA QUIZ!
                ================================""");
        System.out.println("Test your knowledge with " + totalQuestions + " questions.");
        System.out.println("Enter the number of your answer (1-4).\n");

        // Loop through every question in the array
        for (int i = 0; i < questions.length; i++) {
            askQuestion(questions[i], i + 1);
        }

        showResults();
    }

What is a text block?

The triple-quote """ syntax is a Java 21 text block. It lets you write multi-line strings without messy \n escapes or string concatenation.

The start() method prints the banner, loops through every question by calling askQuestion(), and finishes by calling showResults(). Those methods do not exist yet, which is why Eclipse shows errors.

  • Save Quiz.java.
  • Look at the editor. You should see red error markers on askQuestion and showResults because those methods have not been written yet.

Seeing errors on the fields or constructor instead?

Make sure the import java.util.Scanner; line is at the very top of the file, above the class declaration.

Check that the class name is exactly Quiz (capital Q) and matches the filename Quiz.java.

help me fix compilation errors in my Quiz.java constructor

Add input validation and question asking

Right now, your quiz from the previous step crashes if the player types a letter instead of a number. The getUserInput() method fixes this with a while loop that keeps asking until the player enters a valid number between 1 and 4.

  • In Quiz.java, add the askQuestion() method below the closing brace of start():
    private void askQuestion(Question question, int questionNumber) {
        question.display(questionNumber);
        System.out.print("Your answer: ");

        // Get validated input (1-4), then convert to 0-based index
        int userChoice = getUserInput();
        int answerIndex = userChoice - 1;

        if (question.isCorrect(answerIndex)) {
            System.out.println("Correct!");
            score++;
        } else {
            System.out.println("Wrong! The correct answer was: " + question.getCorrectAnswer());
        }
    }

What does this code do?

This method orchestrates one question cycle: display it, get the player's input, check the answer, and update the score.

Notice userChoice - 1. The player types 1-4, but array indices start at 0. Subtracting 1 converts the human-friendly number to the zero-based index the isCorrect() method expects.

  • Add the getUserInput() method below askQuestion():
    private int getUserInput() {
        while (true) {
            if (scanner.hasNextInt()) {
                int input = scanner.nextInt();
                // Only accept 1, 2, 3, or 4
                if (input >= 1 && input <= 4) {
                    return input;
                }
            } else {
                // Consume the invalid token so the loop can continue
                scanner.next();
            }
            System.out.print("Please enter a number between 1 and 4: ");
        }
    }

Why does this never crash?

The while (true) loop only exits when return input runs. That only happens when the player types a valid integer between 1 and 4.

If the player types a letter like "abc", hasNextInt() returns false. The scanner.next() call consumes that bad token so the Scanner is not stuck. Then the loop re-prompts politely.

  • Save Quiz.java.
  • Check the editor. The red marker on askQuestion is gone. One error remains on showResults because that method still does not exist.

Still seeing an error on askQuestion?

Check that the method signature is exactly private void askQuestion(Question question, int questionNumber). The parameter types must match how start() calls it.

Make sure both new methods are inside the Quiz class braces, not accidentally placed outside them.

help me fix the askQuestion error in Quiz.java

Add results and grading with a switch expression

The final method calculates a percentage and uses a switch expression to assign a grade. Unlike a traditional switch statement, a switch expression returns a value directly.

  • Add the showResults() method below getUserInput():
    private void showResults() {
        double percentage = (double) score / totalQuestions * 100;

        System.out.println("""

                ================================
                        QUIZ COMPLETE!
                ================================""");

        System.out.println("Score: " + score + " / " + totalQuestions);
        System.out.println("Percentage: " + String.format("%.1f", percentage) + "%");

        // Switch expression: returns a value based on the score bracket
        String grade = switch ((int) (percentage / 10)) {
            case 10, 9 -> "Excellent! You're a Java master!";
            case 8 -> "Great job! Almost perfect!";
            case 7 -> "Good work! Keep studying!";
            case 6 -> "Not bad, but room to improve!";
            default -> "Keep practicing, you'll get there!";
        };

        System.out.println("Grade: " + grade);
    }

How does the switch expression work?

The expression (int) (percentage / 10) converts a percentage like 85.0 into the integer 8. The switch then matches that integer to a grade message.

Arrow labels -> replace the old case: break; pattern. There is no fall-through, and the entire switch assigns its result directly into the grade variable.

The case 10, 9 syntax means "match either 10 or 9". This handles both a perfect 100% and any score in the 90s.

  • Save Quiz.java.
  • Check the editor. All red error markers should be gone. Your Quiz class is complete.

Seeing an error on the switch expression?

Make sure each arrow case ends with a semicolon after the string (e.g. case 10, 9 -> "Excellent!";). The switch expression itself also ends with a semicolon after the closing brace.

If Eclipse flags the switch as a syntax error, confirm your project is using Java 21. Right-click the project, select Properties, then Java Compiler, and check that the compiler compliance level is 21.

help me fix the switch expression error in my Quiz.java showResults method

Now you need to update QuizApp.java so it delegates all game logic to the Quiz class. The main method should only create questions and hand them off.

  • Open QuizApp.java in the editor.
  • Find the main method. Replace its entire body (the Scanner, score variable, question array, and for loop) with these three lines:
        Question[] questions = createQuestions();
        Quiz quiz = new Quiz(questions);
        quiz.start();

What changed?

The main method went from 35+ lines to just 3. It creates the question data, hands it to a new Quiz object, and starts the game. All the looping, input reading, and scoring now live inside Quiz.

  • Below the main method's closing brace (but still inside the class), add a private static method called createQuestions() that holds your existing question array:
    private static Question[] createQuestions() {
        Question[] questions = new Question[5];

        questions[0] = new Question(
            "What is the correct way to declare a variable in Java?",
            new String[]{"variable x = 5;", "int x = 5;", "x = 5 int;", "declare x = 5;"},
            1
        );
        questions[1] = new Question(
            "Which keyword is used to create a new object in Java?",
            new String[]{"create", "object", "new", "make"},
            2
        );
        questions[2] = new Question(
            "What does the 'void' keyword mean in a method declaration?",
            new String[]{"The method returns an integer", "The method returns nothing", "The method is empty", "The method is private"},
            1
        );
        questions[3] = new Question(
            "Which of these is a valid Java array declaration?",
            new String[]{"int arr[] = new int[5];", "int arr = new int[5];", "array int arr = new[5];", "int[5] arr = new int;"},
            0
        );
        questions[4] = new Question(
            "What is the output of: System.out.println(10 % 3);",
            new String[]{"3", "0", "1", "3.33"},
            2
        );

        return questions;
    }

What does this code do?

This is the same question data you already had. You moved it into its own method to keep main() clean and focused on coordination rather than data.

The method is private static because it belongs to the class itself (not an instance) and nothing outside QuizApp needs to call it.

  • Delete the old Scanner scanner and int score declarations if any remain from the old main method body.
  • Save QuizApp.java.

Before you run the program, what do you think will happen if you type "abc" when asked for your answer? Will it crash like before, or handle it gracefully?

  • Right-click QuizApp.java in the Package Explorer.
  • Select Run As, then Java Application.

You should see the welcome banner appear in the Console. Answer a question or two, then deliberately type abc or 99 when prompted. The quiz politely re-prompts with "Please enter a number between 1 and 4:" instead of crashing.

Complete all 5 questions. You should see your score, percentage, and a grade message like "Excellent! You're a Java master!" for a perfect score.

Seeing a compilation error when you run?

If Eclipse says createQuestions() cannot be resolved, make sure the method is inside the QuizApp class braces and has the exact signature private static Question[] createQuestions().

If the program runs but immediately ends, check that your main method calls quiz.start() and not just new Quiz(questions).

help me debug why my quiz program won't run after adding the Quiz class

✔️ Awesome, I've got everything!

Great. Double check you have saved both Quiz.java and QuizApp.java.

ⓧ I'd like to double check the full code

Scroll up and confirm each section is present in your files, in this order:

Quiz.java:

  • Import statement for java.util.Scanner.
  • Four private fields: questions, score, totalQuestions, scanner.
  • Constructor Quiz(Question[] questions) that initializes all fields.
  • Public start() method with the text block banner and question loop.
  • Private askQuestion() method that displays, gets input, and checks.
  • Private getUserInput() method with the while-true validation loop.
  • Private showResults() method with percentage, text block, and switch expression.

QuizApp.java:

  • A 3-line main() method that calls createQuestions(), creates a Quiz, and calls start().
  • A private static Question[] createQuestions() method with all 5 Question objects and a return statement.

Question.java is unchanged from the previous step.

Your quiz is now a properly structured Java application. QuizApp handles startup, Question holds data, and Quiz runs the game. Next up, you will push this architecture further with a Secret Mission that adds difficulty levels and array filtering.

Secret mission

Add Difficulty Levels

Your quiz currently asks everyone the same 5 questions at the same difficulty. A real quiz app lets the player choose Easy, Medium, or Hard. Can you add a difficulty field, write a filtering method, and build a menu system that ties it all together?

Clean Up Your Resources

Clean Up Your Resources

This project runs entirely on your local machine, so there are no ongoing cloud costs or subscriptions to worry about. Decide whether to keep your project in Eclipse, export a backup, or delete it entirely.

Resources you used:

  • JavaQuizSystem project in your Eclipse workspace (contains QuizApp.java, Question.java, Quiz.java).

Keep everything running

No action needed. Choose this if you are still actively building or want to extend the quiz with more features.

  • The JavaQuizSystem project stays in your Eclipse workspace.
  • You can reopen and modify it anytime by launching Eclipse.

Pause - I'll come back to this later

Export your project as an archive file so you have a backup you can re-import later.

  • Right-click the JavaQuizSystem project in the Package Explorer.
  • Select Export... from the context menu.
  • Expand General and select Archive File.
  • Click Next.
  • Choose a destination folder and file name for your .zip backup, then click Finish.
  • You can now close the project in Eclipse to free up workspace clutter.

Delete - I don't want to use this again

Remove the project and its files from your machine entirely.

  • Right-click the JavaQuizSystem project in the Package Explorer.
  • Click Delete from the context menu.
  • In the confirmation dialog, check Delete project contents on disk (cannot be undone).
  • Click Yes. The project and all its source files are permanently removed.

Nice Work!

Nice Work!

Nice work! You just built a fully interactive console quiz game in Java, structured across three classes that separate data, logic, and startup.

You've learned how to:

  • Build a working interactive quiz game that reads input, validates answers, tracks score, and grades performance using a switch expression.
  • Use arrays and 2D arrays to eliminate repetitive code, after first feeling the pain of duplicating blocks for every question.
  • Design a Question class with private fields, a constructor, getters, and behavior methods, and a Quiz class that separates game logic from data. This mirrors how professional Java applications are built.
  • Secret Mission: Added difficulty filtering using the two-pass array pattern, a transferable technique used throughout Java development.

Ready to quiz yourself?