Java Quiz App

Su Suriya Ravichandran Updated 18 Nov 2026
23 min read ·Lesson 302 of 306

A Java quiz app loads multiple-choice questions from a text file, picks a random set, shuffles the answer options, checks what the player types and prints a score with a review of the missed questions. It also keeps a high-score table on disk. The project brings together records, file parsing, Random, collections and console input in one small, complete program.

This lesson follows the Java File Manager. You model a question, write a question-file parser with line-numbered errors, run the quiz on any input stream, grade the result by topic, save high scores and package everything as quiz.jar. All examples were run on JDK 21.


Model a Quiz Question With a Record

A question has its text, a list of options, the index of the correct option and a topic. The record checks these values when it is created, converts typed letters such as b into an index, and can return a copy with its options in random order.

package com.gocourse.quiz;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/** One multiple-choice question. "correct" is the index of the right option (0 = A). */
public record Question(String text, List<String> options, int correct, String topic) {
    public Question {
        if (text == null || text.isBlank()) throw new IllegalArgumentException("Question text is required");
        if (options.size() < 2 || options.size() > 6) {
            throw new IllegalArgumentException("A question needs 2 to 6 options, found " + options.size());
        }
        if (correct < 0 || correct >= options.size()) {
            throw new IllegalArgumentException("Correct option index out of range: " + correct);
        }
        options = List.copyOf(options); // immutable copy
        topic = (topic == null || topic.isBlank()) ? "general" : topic.strip().toLowerCase();
    }

    /** "A" -> 0, "b" -> 1 ... Returns -1 for anything that is not a valid letter. */
    public int indexOf(String letter) {
        if (letter == null || letter.strip().length() != 1) return -1;
        int index = Character.toUpperCase(letter.strip().charAt(0)) - 'A';
        return index >= 0 && index < options.size() ? index : -1;
    }

    public boolean isCorrect(String letter) {
        return indexOf(letter) == correct;
    }

    public char correctLetter() {
        return (char) ('A' + correct);
    }

    /** Returns a copy with the options in random order; the correct index follows its option. */
    public Question shuffled(Random random) {
        List<Integer> order = new ArrayList<>();
        for (int i = 0; i < options.size(); i++) order.add(i);
        Collections.shuffle(order, random);

        List<String> newOptions = new ArrayList<>();
        for (int oldIndex : order) newOptions.add(options.get(oldIndex));
        return new Question(text, newOptions, order.indexOf(correct), topic);
    }
}
package com.gocourse.quiz;

import java.util.List;
import java.util.Random;

public class QuestionDemo {
    static void print(Question q) {
        System.out.println(q.text() + "  [" + q.topic() + "]");
        for (int i = 0; i < q.options().size(); i++) {
            System.out.println("  " + (char) ('A' + i) + ") " + q.options().get(i));
        }
        System.out.println("  answer: " + q.correctLetter());
    }

    public static void main(String[] args) {
        Question q = new Question("Which keyword creates a new object?",
                List.of("class", "new", "this", "static"), 1, "Basics");
        print(q);
        for (String typed : new String[] {"B", "b", " b ", "A", "E", "", "new"}) {
            System.out.printf("  typed %-6s -> index %2d, correct=%b%n", "'" + typed + "'", q.indexOf(typed), q.isCorrect(typed));
        }

        System.out.println();
        print(q.shuffled(new Random(1)));

        try {
            new Question("Pick one", List.of("only option"), 0, null);
        } catch (IllegalArgumentException e) {
            System.out.println("\nRejected: " + e.getMessage());
        }
    }
}
Which keyword creates a new object?  [basics]
  A) class
  B) new
  C) this
  D) static
  answer: B
  typed 'B'    -> index  1, correct=true
  typed 'b'    -> index  1, correct=true
  typed ' b '  -> index  1, correct=true
  typed 'A'    -> index  0, correct=false
  typed 'E'    -> index -1, correct=false
  typed ''     -> index -1, correct=false
  typed 'new'  -> index -1, correct=false

Which keyword creates a new object?  [basics]
  A) static
  B) class
  C) new
  D) this
  answer: C

Rejected: A question needs 2 to 6 options, found 1

How it works:

  • The compact constructor rejects empty text, fewer than 2 or more than 6 options, and a correct index outside the list. A bad question can never exist, so the rest of the app does not need to check again.
  • List.copyOf(options) stores an unmodifiable copy, so nobody can change the options after the question is built. This follows the immutable style of Java Records.
  • indexOf turns a letter into a number with character arithmetic: 'B' - 'A' is 1. Anything longer than one character, such as new, returns -1.
  • shuffled shuffles a list of the old positions ([0, 1, 2, 3]) and builds the new option list from it. order.indexOf(correct) finds where the right answer moved, so new moved from B to C and the answer letter moved with it.
  • Passing a Random object makes the shuffle repeatable: the same seed always gives the same order, which is useful for testing.

Load Quiz Questions From a Text File

Teachers should be able to write questions without touching Java code. The quiz uses a simple text format: Q: starts a question, - is a wrong option, * is the correct option, # topic: sets the topic and a blank line ends each question.

# topic: basics
Q: Which keyword creates a new object?
- class
* new
- this
package com.gocourse.quiz;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

/**
 * Reads questions in this format, with a blank line between questions:
 *
 *   # topic: basics
 *   Q: Which keyword creates a new object?
 *   - class
 *   * new          (the star marks the correct option)
 *   - this
 */
public class QuestionLoader {

    public static List<Question> load(Path file) throws IOException {
        return parse(Files.readAllLines(file));
    }

    public static List<Question> parse(List<String> lines) {
        List<Question> questions = new ArrayList<>();
        String topic = "general";
        String text = null;
        List<String> options = new ArrayList<>();
        int correct = -1;
        int startLine = 0;

        for (int i = 0; i <= lines.size(); i++) {
            String line = i < lines.size() ? lines.get(i).strip() : ""; // a final blank line ends the last question
            int lineNo = i + 1;

            if (line.isEmpty()) {
                if (text != null) {
                    questions.add(build(text, options, correct, topic, startLine));
                    text = null;
                    options = new ArrayList<>();
                    correct = -1;
                }
            } else if (line.startsWith("# topic:")) {
                topic = line.substring("# topic:".length()).strip();
            } else if (line.startsWith("#")) {
                // comment line: ignore
            } else if (line.startsWith("Q:")) {
                if (text != null) throw error(lineNo, "new question before a blank line");
                text = line.substring(2).strip();
                startLine = lineNo;
            } else if (line.startsWith("-") || line.startsWith("*")) {
                if (text == null) throw error(lineNo, "option without a 'Q:' line");
                if (line.startsWith("*")) {
                    if (correct != -1) throw error(lineNo, "more than one option is marked with *");
                    correct = options.size();
                }
                options.add(line.substring(1).strip());
            } else {
                throw error(lineNo, "unexpected text '" + line + "'");
            }
        }
        return questions;
    }

    private static Question build(String text, List<String> options, int correct, String topic, int lineNo) {
        if (correct == -1) throw error(lineNo, "no option is marked with *");
        try {
            return new Question(text, options, correct, topic);
        } catch (IllegalArgumentException e) {
            throw error(lineNo, e.getMessage());
        }
    }

    private static IllegalArgumentException error(int lineNo, String message) {
        return new IllegalArgumentException("Line " + lineNo + ": " + message);
    }
}
package com.gocourse.quiz;

import java.util.List;

public class LoaderDemo {
    public static void main(String[] args) {
        List<String> good = List.of(
                "# Java basics quiz",
                "# topic: basics",
                "Q: Which keyword creates a new object?",
                "- class",
                "* new",
                "- this",
                "",
                "Q: Which type stores true or false?",
                "- int",
                "* boolean",
                "",
                "# topic: strings",
                "Q: Which method returns the number of characters in a String?",
                "- size()",
                "- count()",
                "* length()");
        for (Question q : QuestionLoader.parse(good)) {
            System.out.println(q.topic() + " | " + q.text() + " | " + q.options() + " | answer " + q.correctLetter());
        }

        List<List<String>> broken = List.of(
                List.of("Q: Pick the loop keyword", "- if", "- for"),
                List.of("Q: Pick the loop keyword", "* for", "* while"),
                List.of("- for", "* while"),
                List.of("Q: Pick the loop keyword", "* for", "while"));
        for (List<String> lines : broken) {
            try {
                QuestionLoader.parse(lines);
            } catch (IllegalArgumentException e) {
                System.out.println("Error: " + e.getMessage());
            }
        }
    }
}
basics | Which keyword creates a new object? | [class, new, this] | answer B
basics | Which type stores true or false? | [int, boolean] | answer B
strings | Which method returns the number of characters in a String? | [size(), count(), length()] | answer C
Error: Line 1: no option is marked with *
Error: Line 3: more than one option is marked with *
Error: Line 1: option without a 'Q:' line
Error: Line 3: unexpected text 'while'
Line starts withMeaning
Q:Question text; starts a new question
-A wrong option
*The correct option (exactly one per question)
# topic:Topic for the following questions
#A comment, ignored
(blank line)End of the current question

How it works:

  • The loop runs one step past the last line (i <= lines.size()) and treats that step as a blank line. This finishes the last question even when the file does not end with an empty line.
  • The parser keeps the current question's parts in local variables and calls build when it reaches a blank line. build creates the Question, so all the record's checks also apply to file input.
  • Every error says which line is wrong, such as Line 3: more than one option is marked with *. Errors from the Question constructor are re-wrapped with the line where that question started.
  • parse takes a List<String>, so it can be tested with in-memory lines, while load reads a real file with Files.readAllLines, as shown in Java Read Files.

Run the Java Quiz and Check Answers

QuizSession asks the questions. It reads from a BufferedReader and writes to a PrintStream instead of using System.in and System.out directly, so the same class works in the console and with scripted answers.

package com.gocourse.quiz;

/** What the player answered for one question. "given" is null when the question was skipped. */
public record Answer(Question question, String given) {
    public boolean correct() {
        return given != null && question.isCorrect(given);
    }

    public boolean skipped() {
        return given == null;
    }
}
package com.gocourse.quiz;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

/** Asks questions on any input/output pair, so it works with the console and with test data. */
public class QuizSession {
    private final BufferedReader in;
    private final PrintStream out;
    private final Random random;

    public QuizSession(BufferedReader in, PrintStream out, Random random) {
        this.in = in;
        this.out = out;
        this.random = random;
    }

    /** Picks "count" random questions, shuffles their options and asks them one by one. */
    public List<Answer> run(List<Question> bank, int count) throws IOException {
        List<Question> pool = new ArrayList<>(bank);
        Collections.shuffle(pool, random);
        List<Question> chosen = pool.subList(0, Math.min(count, pool.size()));

        List<Answer> answers = new ArrayList<>();
        for (int i = 0; i < chosen.size(); i++) {
            Question question = chosen.get(i).shuffled(random);
            out.printf("%nQuestion %d of %d  [%s]%n%s%n", i + 1, chosen.size(), question.topic(), question.text());
            for (int o = 0; o < question.options().size(); o++) {
                out.printf("  %c) %s%n", 'A' + o, question.options().get(o));
            }
            String given = ask(question);
            Answer answer = new Answer(question, given);
            answers.add(answer);
            if (answer.skipped()) {
                out.println("Skipped. The answer was " + question.correctLetter());
            } else if (answer.correct()) {
                out.println("Correct!");
            } else {
                out.println("Wrong. The answer was " + question.correctLetter());
            }
        }
        return answers;
    }

    /** Reads until a valid letter or an empty line (skip). End of input also counts as a skip. */
    private String ask(Question question) throws IOException {
        char last = (char) ('A' + question.options().size() - 1);
        while (true) {
            out.print("Your answer (A-" + last + ", Enter to skip): ");
            String line = in.readLine();
            if (line == null) out.println();
            if (line == null || line.isBlank()) return null;
            if (question.indexOf(line) >= 0) return line.strip().toUpperCase();
            out.println("Please type a letter from A to " + last + ".");
        }
    }
}

The demo plays the quiz with a scripted player. An anonymous subclass of BufferedReader prints each typed line, so you can see the answers in the output.

package com.gocourse.quiz;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.Random;

public class SessionDemo {
    public static void main(String[] args) throws Exception {
        List<Question> bank = List.of(
                new Question("Which keyword creates a new object?", List.of("class", "new", "this", "static"), 1, "basics"),
                new Question("Which type stores true or false?", List.of("int", "boolean", "char"), 1, "basics"),
                new Question("Which method returns a String's size?", List.of("size()", "count()", "length()"), 2, "strings"));

        // the "player": one answer per line, including a typo and a skip
        String typed = "c\nx\na\n\n";
        BufferedReader player = new BufferedReader(new StringReader(typed)) {
            @Override
            public String readLine() throws IOException {
                String line = super.readLine();
                System.out.println(line); // show what the "player" typed
                return line;
            }
        };
        QuizSession session = new QuizSession(player, System.out, new Random(7));
        List<Answer> answers = session.run(bank, 3);

        System.out.println();
        for (Answer a : answers) {
            System.out.printf("%-40s given=%-4s correct=%-5b skipped=%b%n",
                    a.question().text(), a.given(), a.correct(), a.skipped());
        }
    }
}

Question 1 of 3  [basics]
Which keyword creates a new object?
  A) static
  B) class
  C) new
  D) this
Your answer (A-D, Enter to skip): c
Correct!

Question 2 of 3  [strings]
Which method returns a String's size?
  A) size()
  B) length()
  C) count()
Your answer (A-C, Enter to skip): x
Please type a letter from A to C.
Your answer (A-C, Enter to skip): a
Wrong. The answer was B

Question 3 of 3  [basics]
Which type stores true or false?
  A) int
  B) boolean
  C) char
Your answer (A-C, Enter to skip): 
Skipped. The answer was B

Which keyword creates a new object?      given=C    correct=true  skipped=false
Which method returns a String's size?    given=A    correct=false skipped=false
Which type stores true or false?         given=null correct=false skipped=true

How it works:

  • run copies the question bank, shuffles it with Collections.shuffle(pool, random) and keeps the first count questions with subList. Each chosen question is then shuffled again with shuffled(random), so both the question order and the option order change between games.
  • ask loops until it gets a valid letter. The typo x prints a hint and asks again instead of counting as a wrong answer.
  • An empty line means "skip". readLine() returns null at the end of input (for example, Ctrl+D or a finished script), which is also treated as a skip so the program never crashes.
  • Answer stores null for a skipped question. correct() checks for null first, and skipped() makes the intent clear when printing results.

Score the Quiz by Topic and Review Mistakes

QuizResult turns the list of answers into a score, a percentage, a grade, a per-topic breakdown and a review list. A nested TopicScore record holds the correct and total counts for each topic.

package com.gocourse.quiz;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/** The outcome of one quiz: score, grade, per-topic breakdown and the questions to review. */
public record QuizResult(String player, List<Answer> answers) {
    public record TopicScore(int correct, int total) {
        TopicScore plus(TopicScore other) {
            return new TopicScore(correct + other.correct, total + other.total);
        }
    }

    public int score() {
        return (int) answers.stream().filter(Answer::correct).count();
    }

    public int total() {
        return answers.size();
    }

    public double percent() {
        return total() == 0 ? 0 : 100.0 * score() / total();
    }

    public String grade() {
        double p = percent();
        if (p >= 90) return "A (excellent)";
        if (p >= 75) return "B (good)";
        if (p >= 60) return "C (pass)";
        return "Not yet - review and try again";
    }

    public Map<String, TopicScore> byTopic() {
        Map<String, TopicScore> topics = new TreeMap<>();
        for (Answer a : answers) {
            topics.merge(a.question().topic(), new TopicScore(a.correct() ? 1 : 0, 1), TopicScore::plus);
        }
        return topics;
    }

    public List<Answer> toReview() {
        return answers.stream().filter(a -> !a.correct()).toList();
    }

    public String report() {
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("%s scored %d/%d (%.0f%%) - grade %s%n", player, score(), total(), percent(), grade()));
        byTopic().forEach((topic, s) -> sb.append(String.format("  %-10s %d/%d%n", topic, s.correct(), s.total())));
        List<Answer> review = toReview();
        if (!review.isEmpty()) {
            sb.append("Review:\n");
            for (Answer a : review) {
                Question q = a.question();
                sb.append(String.format("  %s%n    you: %s, correct: %c) %s%n", q.text(),
                        a.skipped() ? "skipped" : a.given() + ") " + q.options().get(q.indexOf(a.given())),
                        q.correctLetter(), q.options().get(q.correct())));
            }
        }
        return sb.toString();
    }
}
package com.gocourse.quiz;

import java.util.List;

public class ResultDemo {
    public static void main(String[] args) {
        Question newKeyword = new Question("Which keyword creates a new object?", List.of("class", "new", "this"), 1, "basics");
        Question bool = new Question("Which type stores true or false?", List.of("int", "boolean"), 1, "basics");
        Question length = new Question("Which method returns a String's size?", List.of("size()", "length()"), 1, "strings");
        Question equals = new Question("How do you compare String contents?", List.of("==", "equals()"), 1, "strings");
        Question loop = new Question("Which loop always runs at least once?", List.of("for", "while", "do-while"), 2, "loops");

        QuizResult result = new QuizResult("Priya", List.of(
                new Answer(newKeyword, "B"),
                new Answer(bool, "B"),
                new Answer(length, "B"),
                new Answer(equals, "A"),   // wrong
                new Answer(loop, null)));  // skipped
        System.out.print(result.report());

        System.out.println();
        QuizResult perfect = new QuizResult("Arun", List.of(new Answer(newKeyword, "b"), new Answer(loop, "C")));
        System.out.print(perfect.report());
    }
}
Priya scored 3/5 (60%) - grade C (pass)
  basics     2/2
  loops      0/1
  strings    1/2
Review:
  How do you compare String contents?
    you: A) ==, correct: B) equals()
  Which loop always runs at least once?
    you: skipped, correct: C) do-while

Arun scored 2/2 (100%) - grade A (excellent)
  basics     1/1
  loops      1/1
PercentageGrade
90 and aboveA (excellent)
75 to 89B (good)
60 to 74C (pass)
Below 60Not yet - review and try again

How it works:

  • score() counts correct answers with a stream, and percent() returns 0 for an empty quiz to avoid dividing by zero.
  • byTopic uses Map.merge: the first answer of a topic stores TopicScore(1, 1) or TopicScore(0, 1), and later answers are added with TopicScore::plus. A TreeMap keeps topics in alphabetical order.
  • toReview() returns wrong and skipped answers, because both show what the player should study.
  • report() builds the whole text with a StringBuilder and String.format, as covered in Java String Format. It shows the player's choice next to the correct option, or skipped.

Save Quiz High Scores to a File

Every finished game is appended to a tab-separated file. The leaderboard reads the file, ranks the entries and returns the best few.

package com.gocourse.quiz;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/** Appends every finished quiz to a tab-separated file and reads back the best results. */
public class HighScores {
    public record Entry(String player, int score, int total, LocalDate date) {
        double percent() {
            return 100.0 * score / total;
        }
    }

    /** Best percentage first; on a tie, more questions first; then the earlier date. */
    static final Comparator<Entry> RANKING = Comparator
            .comparingDouble(Entry::percent).reversed()
            .thenComparing(Comparator.comparingInt(Entry::total).reversed())
            .thenComparing(Entry::date);

    private final Path file;

    public HighScores(Path file) {
        this.file = file;
    }

    public void record(QuizResult result, LocalDate date) throws IOException {
        String player = result.player().replace("\t", " ");
        String line = String.join("\t", player, String.valueOf(result.score()),
                String.valueOf(result.total()), date.toString()) + System.lineSeparator();
        Files.writeString(file, line, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    }

    public List<Entry> top(int count) throws IOException {
        if (Files.notExists(file)) return List.of();
        List<Entry> entries = new ArrayList<>();
        for (String line : Files.readAllLines(file)) {
            String[] f = line.split("\t");
            if (f.length != 4) continue; // skip damaged lines instead of failing
            entries.add(new Entry(f[0], Integer.parseInt(f[1]), Integer.parseInt(f[2]), LocalDate.parse(f[3])));
        }
        return entries.stream().filter(e -> e.total() > 0).sorted(RANKING).limit(count).toList();
    }
}
package com.gocourse.quiz;

import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;

public class ScoresDemo {
    static QuizResult fake(String player, int correct, int total) {
        Question q = new Question("2 + 2 = ?", List.of("3", "4"), 1, "math");
        List<Answer> answers = new java.util.ArrayList<>();
        answers.addAll(Collections.nCopies(correct, new Answer(q, "B")));
        answers.addAll(Collections.nCopies(total - correct, new Answer(q, "A")));
        return new QuizResult(player, answers);
    }

    public static void main(String[] args) throws Exception {
        Path file = Path.of("scores-demo.tsv");
        Files.deleteIfExists(file);
        HighScores scores = new HighScores(file);

        scores.record(fake("Priya", 6, 10), LocalDate.of(2026, 11, 14));
        scores.record(fake("Arun", 9, 10), LocalDate.of(2026, 11, 15));
        scores.record(fake("Meena", 5, 5), LocalDate.of(2026, 11, 16));
        scores.record(fake("Priya", 10, 10), LocalDate.of(2026, 11, 17));
        scores.record(fake("Karthik", 9, 10), LocalDate.of(2026, 11, 17));
        Files.writeString(file, "broken line\n", java.nio.file.StandardOpenOption.APPEND);

        System.out.println("Top 4:");
        int rank = 1;
        for (HighScores.Entry e : scores.top(4)) {
            System.out.printf("  %d. %-8s %2d/%-2d %5.1f%%  %s%n", rank++, e.player(), e.score(), e.total(), e.percent(), e.date());
        }
        Files.delete(file);
    }
}
Top 4:
  1. Priya    10/10 100.0%  2026-11-17
  2. Meena     5/5  100.0%  2026-11-16
  3. Arun      9/10  90.0%  2026-11-15
  4. Karthik   9/10  90.0%  2026-11-17

How it works:

  • StandardOpenOption.CREATE, StandardOpenOption.APPEND creates the file the first time and adds one line per game afterwards. Old scores are never rewritten.
  • RANKING sorts by percentage (highest first), then by number of questions, so Priya's 10/10 beats Meena's 5/5. If both are equal, the earlier date wins, so Arun's 90% from 15 November ranks above Karthik's from 17 November.
  • .reversed() is applied to the first comparator only. The tie-breakers are added afterwards with thenComparing, and the question-count tie-breaker has its own .reversed().
  • The line broken line has the wrong number of fields and is skipped, so a damaged file does not stop the game. Tabs in player names are replaced with spaces before saving, since a tab would break the format.

Build the Java Quiz App for the Console

QuizApp wires everything together: it loads the question file, asks for the player's name, runs the session, prints the report and updates the leaderboard. Settings come from system properties with sensible defaults.

package com.gocourse.quiz;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.time.LocalDate;
import java.util.List;
import java.util.Random;

/** Console quiz: java -jar quiz.jar [questions-file] */
public class QuizApp {
    public static void main(String[] args) throws IOException {
        Path questionsFile = Path.of(args.length > 0 ? args[0] : "questions.txt");
        int count = Integer.getInteger("quiz.count", 5);
        Long seed = Long.getLong("quiz.seed"); // optional, for repeatable runs
        Random random = seed == null ? new Random() : new Random(seed);
        HighScores highScores = new HighScores(Path.of(System.getProperty("quiz.scores", "scores.tsv")));
        LocalDate today = LocalDate.parse(System.getProperty("quiz.today", LocalDate.now().toString()));

        List<Question> bank;
        try {
            bank = QuestionLoader.load(questionsFile);
        } catch (NoSuchFileException e) {
            System.out.println("Question file not found: " + questionsFile);
            System.exit(1);
            return;
        } catch (IllegalArgumentException e) {
            System.out.println("Bad question file " + questionsFile + ": " + e.getMessage());
            System.exit(1);
            return;
        }

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.printf("Loaded %d questions from %s. You will get %d.%n", bank.size(), questionsFile,
                Math.min(count, bank.size()));
        System.out.print("Your name: ");
        String name = in.readLine();
        if (name == null || name.isBlank()) name = "Player";

        List<Answer> answers = new QuizSession(in, System.out, random).run(bank, count);
        QuizResult result = new QuizResult(name.strip(), answers);

        System.out.println();
        System.out.print(result.report());
        highScores.record(result, today);

        System.out.println("High scores:");
        int rank = 1;
        for (HighScores.Entry e : highScores.top(5)) {
            System.out.printf("  %d. %-10s %d/%d  %s%n", rank++, e.player(), e.score(), e.total(), e.date());
        }
    }
}
System propertyDefaultPurpose
quiz.count5Number of questions per game
quiz.seedrandomFixed seed for repeatable games and demos
quiz.scoresscores.tsvHigh-score file
quiz.todaytoday's dateDate stored with the score (for demos and tests)

How it works:

  • Integer.getInteger("quiz.count", 5) reads a system property as a number, and Long.getLong("quiz.seed") returns null when the property is not set. With no seed, new Random() gives a different game every time.
  • A missing file is reported through NoSuchFileException, and a badly written file through the parser's IllegalArgumentException. Both print a clear message and exit with code 1.
  • return after System.exit(1) is never reached at run time, but the compiler needs it to know that bank is always assigned afterwards.
  • One BufferedReader is shared by the name prompt and the session, so no typed input is lost between them.

Real-World Example: Run a Java Basics Quiz

quiz-app/
├── java-basics.txt
└── src/
    └── com/
        └── gocourse/
            └── quiz/
                ├── Answer.java
                ├── HighScores.java
                ├── Question.java
                ├── QuestionLoader.java
                ├── QuizApp.java
                ├── QuizResult.java
                └── QuizSession.java

The question file java-basics.txt holds eight questions in four topics:

# Java basics quiz for GOCOURSE
# topic: basics
Q: Which keyword creates a new object?
- class
* new
- this
- static

Q: Which type stores true or false?
- int
* boolean
- char

Q: Which method is the entry point of a Java program?
- start()
- run()
* main()

# topic: strings
Q: Which method returns the number of characters in a String?
- size()
- count()
* length()

Q: How do you compare the contents of two Strings?
- ==
* equals()
- compare()

# topic: loops
Q: Which loop always runs its body at least once?
- for
- while
* do-while

Q: Which keyword jumps to the next loop iteration?
- break
* continue
- return

# topic: oop
Q: Which keyword makes a class inherit from another class?
- implements
* extends
- inherits
cd quiz-app
javac -d out src/com/gocourse/quiz/*.java
jar --create --file quiz.jar --main-class com.gocourse.quiz.QuizApp -C out .

# fixed seeds and dates make this demo repeatable; leave them out for real games
java -Dquiz.seed=3 -Dquiz.today=2026-11-17 -jar quiz.jar java-basics.txt

Arun plays first:

Loaded 8 questions from java-basics.txt. You will get 5.
Your name: Arun

Question 1 of 5  [basics]
Which method is the entry point of a Java program?
  A) main()
  B) start()
  C) run()
Your answer (A-C, Enter to skip): a
Correct!

Question 2 of 5  [strings]
How do you compare the contents of two Strings?
  A) ==
  B) compare()
  C) equals()
Your answer (A-C, Enter to skip): c
Correct!

Question 3 of 5  [strings]
Which method returns the number of characters in a String?
  A) size()
  B) length()
  C) count()
Your answer (A-C, Enter to skip): 
Skipped. The answer was B

Question 4 of 5  [loops]
Which keyword jumps to the next loop iteration?
  A) return
  B) break
  C) continue
Your answer (A-C, Enter to skip): b
Wrong. The answer was C

Question 5 of 5  [basics]
Which type stores true or false?
  A) int
  B) char
  C) boolean
Your answer (A-C, Enter to skip): c
Correct!

Arun scored 3/5 (60%) - grade C (pass)
  basics     2/2
  loops      0/1
  strings    1/2
Review:
  Which method returns the number of characters in a String?
    you: skipped, correct: B) length()
  Which keyword jumps to the next loop iteration?
    you: B) break, correct: C) continue
High scores:
  1. Arun       3/5  2026-11-17

The next day Priya plays with a different seed (-Dquiz.seed=11 -Dquiz.today=2026-11-18):

Loaded 8 questions from java-basics.txt. You will get 5.
Your name: Priya

Question 1 of 5  [basics]
Which type stores true or false?
  A) boolean
  B) int
  C) char
Your answer (A-C, Enter to skip): a
Correct!

Question 2 of 5  [loops]
Which keyword jumps to the next loop iteration?
  A) continue
  B) break
  C) return
Your answer (A-C, Enter to skip): 9
Please type a letter from A to C.
Your answer (A-C, Enter to skip): a
Correct!

Question 3 of 5  [strings]
How do you compare the contents of two Strings?
  A) equals()
  B) compare()
  C) ==
Your answer (A-C, Enter to skip): a
Correct!

Question 4 of 5  [basics]
Which method is the entry point of a Java program?
  A) start()
  B) run()
  C) main()
Your answer (A-C, Enter to skip): c
Correct!

Question 5 of 5  [basics]
Which keyword creates a new object?
  A) new
  B) class
  C) this
  D) static
Your answer (A-D, Enter to skip): a
Correct!

Priya scored 5/5 (100%) - grade A (excellent)
  basics     3/3
  loops      1/1
  strings    1/1
High scores:
  1. Priya      5/5  2026-11-18
  2. Arun       3/5  2026-11-17

The file scores.tsv now holds both games (tabs between fields):

Arun	3	5	2026-11-17
Priya	5	5	2026-11-18

If the question file has a mistake, the quiz does not start:

$ java -jar quiz.jar broken.txt
Bad question file broken.txt: Line 1: unexpected text 'x'
$ java -jar quiz.jar missing.txt
Question file not found: missing.txt

How it works:

  1. Different games from one file. Seed 3 and seed 11 picked different questions in a different order, and the options were shuffled too, so the correct letter is not always in the same place.
  2. Forgiving input. Lowercase letters are accepted, the typo 9 only triggers a hint, and pressing Enter skips a question.
  3. Useful feedback. Arun's report shows 2/2 in basics but 0/1 in loops, and the review lists the exact questions he missed or skipped with the correct options.
  4. A persistent leaderboard. Each game adds one line to scores.tsv, and Priya's 100% puts her above Arun's 60%.
  5. Safe start-up. A broken or missing question file stops the app with a line-numbered message before any question is asked.

The next project, the Java REST API Project, turns data like this into a web service that other programs can call over HTTP.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Quiz App and get answers drawn from it.

Signed-in readers only.