Java Tutorial
Java Project: Quiz Game
A scored quiz from a list of questions. Print each prompt, check the answer, and tally.
What you will build
Each item has a prompt and the correct answer. Loop, compare with equalsIgnoreCase, and print the score.
Questions and score
Example
record Item(String prompt, String answer) {}
public class Main {
public static void main(String[] args) {
Item[] quiz = {
new Item("2 + 2?", "4"),
new Item("Java file suffix?", "java"),
new Item("Keyword for a class?", "class")
};
String[] replies = {"4", "java", "struct"};
int score = 0;
for (int i = 0; i < quiz.length; i++) {
boolean ok = quiz[i].answer().equalsIgnoreCase(replies[i]);
if (ok) score++;
System.out.println(quiz[i].prompt() + " " + (ok ? "correct" : "wrong"));
}
System.out.println("score: " + score + "/" + quiz.length);
}
}Practice
- Compile the complete program at
/java/try. - Change one input value and compile again.
- Replace a hardcoded number with
Scannerwhen you want typed input.