Java
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Java
-
Section 4: Collections Framework
-
Section 5: Exception Handling
-
Section 6: Generics
-
Section 7: Functional Java
-
Section 8: Concurrency
-
Section 9: I/O and NIO
-
Section 10: JVM Internals
-
Section 11: Modern Java Features
-
Section 12: Build Tools and Project Structure
-
Section 13: Testing
-
Section 14: Databases and Persistence
-
Section 15: Networking
-
Section 16: Design and Best Practices
-
Section 17: Reflection and Annotations
-
Section 18: Logging and Diagnostics
-
Section 19: Date, Time, and Internationalization
-
Section 20: Java Platform Module System
-
Section 21: Security in Java
-
Section 22: Advanced Collections and Data Structures
-
Section 23: More Concurrency Patterns
-
Section 24: Compression, Files, and System Integration
-
Section 25: GUI Programming
-
Section 26: Practical Projects
-
Section 27: Data Structures and Algorithms
-
Section 28: Interview and Algorithm Practice
-
Section 29: JSON and Data Interchange
-
Section 30: More Concurrency Utilities
-
Section 31: More Collections and Streams Practice
-
Section 32: More File and System Programming
-
Section 33: Standard Library Deep Dive
-
Section 34: More Practice and Drills
-
Section 35: More Testing and Quality
-
Section 36: More Design Patterns and Architecture
-
Section 37: Career and Ecosystem
-
Section 38: More OOP and Architecture Practice
-
Section 39: More Enterprise Concepts
-
Section 40: Advanced JavaFX
-
Section 41: More Interview Practice
224: Building a Simple Quiz Application
Alright, let's actually build something. We've spent a lot of time on the theory of classes and lists, but it's time to put them together. I want to build a simple quiz application—nothing fancy, just a console app that asks a few questions and tells you your score at the end. I'll walk you through how I'd tackle this, including the mistakes I'll probably make along the way.
Modeling the Question
First off, I need a way to represent a single question. I could just use a bunch of arrays, but that's a nightmare to maintain. I'll create a Question class. I need the text of the question, the possible options, and the correct answer.
public class Question {
String prompt;
String answer;
public Question(String prompt, String answer) {
this.prompt = prompt;
this.answer = answer;
}
}
Wait, looking at this, it's a bit too simple. If I just have a prompt and an answer, the user has to guess the exact word. That's frustrating. I'll add an array of options so the user can just pick 'A', 'B', or 'C'. I'll update the class to handle that.
public class Question {
String prompt;
String[] options;
char correctOption;
public Question(String prompt, String[] options, char correctOption) {
this.prompt = prompt;
this.options = options;
this.correctOption = correctOption;
}
}
The String Comparison Trap
Now, let's try to run this. I'll create a list of questions and a loop to iterate through them. I'll use a Scanner to get the user's input. Here is my first attempt at the logic inside the loop:
Scanner scanner = new Scanner(System.in);
int score = 0;
for (Question q : quizBank) {
System.out.println(q.prompt);
for (int i = 0; i < q.options.length; i++) {
System.out.println((i + 1) + ": " + q.options[i]);
}
String userInput = scanner.next();
if (userInput == "A") { // Let's assume I'm checking for a specific letter
score++;
}
}
I ran this, and it failed. Even when I typed 'A', the score didn't go up. Why? Right—I did the classic Java rookie mistake: using == to compare strings. In Java, == checks if the two objects are the same memory reference, not if their content is the same. I need to use .equals() or, even better, since I'm using char for the correct option, I should just read the input as a character.
Let's fix that and make it case-insensitive so the user doesn't get penalized for hitting the shift key.
char userInput = scanner.next().toUpperCase().charAt(0);
if (userInput == q.correctOption) {
System.out.println("Correct!");
score++;
} else {
System.out.println("Wrong. The answer was " + q.correctOption);
}
Tying it all together
Now that the logic is solid, I don't want my main method to be a giant wall of code. It's cleaner to move the quiz execution into its own method or class. I'll create a QuizEngine class that takes a list of questions and handles the scoring. This makes the code reusable; if I want to add a "Science Quiz" and a "History Quiz" later, I don't have to rewrite the loop.
Here is how the final structure looks in my head: a Question POJO (Plain Old Java Object), a QuizEngine to handle the loop, and a Main class to define the specific questions and start the engine.
import java.util.*;
class Question {
String prompt;
String[] options;
char correctOption;
public Question(String prompt, String[] options, char correctOption) {
this.prompt = prompt;
this.options = options;
this.correctOption = correctOption;
}
}
class QuizEngine {
public int runQuiz(List<Question> questions) {
Scanner scanner = new Scanner(System.in);
int score = 0;
for (Question q : questions) {
System.out.println("\n" + q.prompt);
char label = 'A';
for (String option : q.options) {
System.out.println(label + ") " + option);
label++;
}
System.out.print("Your answer: ");
char input = scanner.next().toUpperCase().charAt(0);
if (input == q.correctOption) {
System.out.println("Nice!");
score++;
} else {
System.out.println("Nope, it was " + q.correctOption);
}
}
return score;
}
}
public class Main {
public static void main(String[] args) {
List<Question> javaQuiz = new ArrayList<>();
javaQuiz.add(new Question("Which keyword is used to create a class?",
new String[]{"class", "struct", "object", "new"}, 'A'));
javaQuiz.add(new Question("What is the default value of a boolean?",
new String[]{"true", "false", "null", "0"}, 'B'));
QuizEngine engine = new QuizEngine();
int finalScore = engine.runQuiz(javaQuiz);
System.out.println("\nYour final score: " + finalScore + "/" + javaQuiz.size());
}
}
Notice how I used a char label = 'A' inside the loop. By incrementing a character, Java automatically moves to 'B', 'C', and so on. It's a neat little trick to avoid manually typing out letters for every option.
📋 Practical Task
Build a Space Exploration Trivia Engine
Your task is to expand upon the Quiz Application. Instead of a Java quiz, build a "Space Exploration Trivia Engine" with the following specific requirements:
- Create at least five
Questionobjects related to astronomy or space flight. - Modify the
QuizEngineso that it tracks not just the total score, but also which specific questions the user got wrong. - At the end of the quiz, print a "Review Sheet" that lists only the questions the user missed, showing the correct answer for each.
- Implement a simple input validation check: if the user enters a character that isn't one of the provided options (e.g., they type 'Z' when only 'A', 'B', 'C', 'D' exist), the program should tell them "Invalid Option" and ask for the answer to that same question again.
There are no comments for now.