Skip to content
Java project #03Beginner

Quiz Game

A multiple-choice quiz with answer validation, streak bonuses, a per-topic score breakdown and a review of every wrong answer.

Estimated time
~2 hours to build
Files
4 files · 278 lines
Technologies
Java 21, Records, List.of, Streams, Scanner

Introduction

Quizzes are a fun way to practise records, lists and streams. Each question is a record holding its topic, text, options, correct index and an explanation; the game keeps a list of answers and turns it into a score report at the end.

Problem statement

Ask a sequence of multiple-choice questions grouped by topic. Accept answers a–d (any case) and ask again for anything else. Award 10 points per correct answer and a 5-point bonus for every correct answer that extends a streak to three or more. At the end — or if input ends early — print the number correct, the score with bonus, a per-topic breakdown, a review of wrong answers with explanations and an overall message.

Objectives

  • Model fixed data with records and List.of
  • Validate single-character input
  • Track streaks and bonus points
  • Summarise results with streams

Features

  • Topics and explanations for every question
  • Re-prompts on invalid answers
  • Streak bonus scoring
  • Per-topic bar breakdown and wrong-answer review
  • Handles input ending early

Concepts demonstrated

  • Records
  • Immutable collections
  • Game loop
  • Streams: filter, count, distinct
  • Formatted output

System architecture

Question and Answer are records; Answer.correct() compares the chosen index with the question's answer. QUESTIONS is an immutable list. The main loop prints each question, reads answers until one is valid, records an Answer and updates the score and streak. report is a separate method so it can be called both at the end and when input runs out; it uses streams to count correct answers, list topics in order of first appearance and select wrong answers for the review.

Folder structure

TextProject tree
quiz-game/
├── README.md
├── src/Main.java
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

src/Main.java

94 lines
Javasrc/Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Quiz Game — multiple-choice questions grouped by topic, answer validation, scoring with
* a streak bonus, a per-topic breakdown and a review of every wrong answer.
*/
public class Main {
record Question(String topic, String text, String[] options, int answer, String explanation) { }
record Answer(Question question, int chosen) {
boolean correct() { return chosen == question.answer(); }
}
static final List<Question> QUESTIONS = List.of(
new Question("Basics", "Which keyword creates an object?", new String[]{"class", "new", "this", "void"}, 1, "new allocates and initialises an object."),
new Question("Basics", "What is the size of an int in Java?", new String[]{"16 bits", "32 bits", "64 bits", "It depends on the OS"}, 1, "Java fixes int at 32 bits on every platform."),
new Question("Strings", "How should two strings be compared for equal content?", new String[]{"==", "equals()", "compare()", "="}, 1, "== compares references; equals compares characters."),
new Question("Strings", "What does \"java\".charAt(1) return?", new String[]{"'j'", "'a'", "'v'", "An error"}, 1, "Indexes start at 0, so index 1 is 'a'."),
new Question("OOP", "Which keyword lets a class reuse another class's members?", new String[]{"implements", "extends", "import", "super"}, 1, "A class extends a superclass and implements interfaces."),
new Question("OOP", "Can an abstract class be instantiated with new?", new String[]{"Yes", "No", "Only if it has a constructor", "Only inside the same package"}, 1, "Abstract classes must be subclassed first."));
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("=== Java Quiz === Answer with a, b, c or d.");
List<Answer> answers = new ArrayList<>();
int score = 0, streak = 0, bonus = 0;
for (int i = 0; i < QUESTIONS.size(); i++) {
Question q = QUESTIONS.get(i);
System.out.printf("%nQ%d [%s] %s%n", i + 1, q.topic(), q.text());
for (int j = 0; j < q.options().length; j++) System.out.printf(" %c) %s%n", 'a' + j, q.options()[j]);
int chosen = -1;
while (chosen < 0) {
System.out.print("Your answer: ");
if (!in.hasNextLine()) {
System.out.println("\nInput ended; the remaining questions are skipped.");
report(answers, score, bonus);
return;
}
String text = in.nextLine().trim().toLowerCase();
System.out.println(text);
if (text.length() == 1 && text.charAt(0) >= 'a' && text.charAt(0) < 'a' + q.options().length) chosen = text.charAt(0) - 'a';
else System.out.println("Please type a letter from a to " + (char) ('a' + q.options().length - 1) + ".");
}
Answer a = new Answer(q, chosen);
answers.add(a);
if (a.correct()) {
score += 10;
streak++;
if (streak >= 3) { // 5 bonus points for every answer in a streak of 3 or more
bonus += 5;
System.out.println("Correct! Streak of " + streak + " (+5 bonus)");
} else {
System.out.println("Correct!");
}
} else {
streak = 0;
System.out.printf("Wrong - the answer is %c) %s%n", 'a' + q.answer(), q.options()[q.answer()]);
}
}
report(answers, score, bonus);
}
static void report(List<Answer> answers, int score, int bonus) {
long right = answers.stream().filter(Answer::correct).count();
System.out.println("\n===== Result =====");
System.out.printf("Correct: %d/%d Score: %d + %d bonus = %d%n", right, answers.size(), score, bonus, score + bonus);
System.out.println("By topic:");
List<String> topics = answers.stream().map(a -> a.question().topic()).distinct().toList();
for (String t : topics) {
long total = answers.stream().filter(a -> a.question().topic().equals(t)).count();
long ok = answers.stream().filter(a -> a.question().topic().equals(t) && a.correct()).count();
System.out.printf(" %-8s %d/%d %s%n", t, ok, total, "#".repeat((int) ok) + ".".repeat((int) (total - ok)));
}
List<Answer> wrong = answers.stream().filter(a -> !a.correct()).toList();
if (wrong.isEmpty()) {
System.out.println("Perfect score!");
} else {
System.out.println("Review:");
for (Answer a : wrong)
System.out.printf(" - %s%n you chose: %s | correct: %s%n %s%n", a.question().text(), a.question().options()[a.chosen()],
a.question().options()[a.question().answer()], a.question().explanation());
}
double pct = answers.isEmpty() ? 0 : right * 100.0 / answers.size();
System.out.println(pct >= 80 ? "Excellent!" : pct >= 50 ? "Good effort - review the topics above." : "Keep practising!");
}
}

What each file does

src/Main.java
The question bank, the answer loop with streak scoring, and the report.

How to run it

Compile

Terminal
javac -d out $(find src -name "*.java")
# Windows PowerShell: javac -d out (Get-ChildItem -Recurse src -Filter *.java).FullName

Run

Terminal
java -cp out Main

Test against the expected output

Terminal
java -cp out Main < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | java -cp out Main > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
=== Java Quiz === Answer with a, b, c or d.
Q1 [Basics] Which keyword creates an object?
a) class
b) new
c) this
d) void
Your answer: b
Correct!
Q2 [Basics] What is the size of an int in Java?
a) 16 bits
b) 32 bits
c) 64 bits
d) It depends on the OS
Your answer: b
Correct!
Q3 [Strings] How should two strings be compared for equal content?
a) ==
b) equals()
c) compare()
d) =
Your answer: e
Please type a letter from a to d.
Your answer: b
Correct! Streak of 3 (+5 bonus)
Q4 [Strings] What does "java".charAt(1) return?
a) 'j'
b) 'a'
c) 'v'
d) An error
Your answer: b
Correct! Streak of 4 (+5 bonus)
Q5 [OOP] Which keyword lets a class reuse another class's members?
a) implements
b) extends
c) import
d) super
Your answer: a
Wrong - the answer is b) extends
Q6 [OOP] Can an abstract class be instantiated with new?
a) Yes
b) No
c) Only if it has a constructor
d) Only inside the same package
Your answer: b
Correct!
===== Result =====
Correct: 5/6 Score: 50 + 10 bonus = 60
By topic:
Basics 2/2 ##
Strings 2/2 ##
OOP 1/2 #.
Review:
- Which keyword lets a class reuse another class's members?
you chose: implements | correct: extends
A class extends a superclass and implements interfaces.
Excellent!
Input
b
B
e
b
b
a
b
b

Testing

  • Run with tests/sample-input.txt and compare with tests/expected-output.txt.
  • The answer e is rejected and the question is asked again.
  • Answers 3 and 4 extend the streak, earning two bonuses (+10).
  • The one wrong answer (Q5) appears in the review with its explanation.

Common errors

Upper-case answers are rejected

Normalise with toLowerCase() before checking the letter.

ArrayIndexOutOfBoundsException for answer 'e'

Check that the letter is within the option range before converting it to an index.

Possible improvements

  • Load questions from a text file
  • Shuffle questions and options with a seeded Random
  • Add a time limit per question

Additional challenges

  1. 1Let the user choose topics before starting.
  2. 2Remember the best score in a file.
  3. 3Support questions with more than one correct option.

Built and tested it yourself? Mark it to update your dashboard.