CodeBlanks Logo Icon CodeBlanks

Quiz model

Design the Question and Quiz class skeleton.

Project: Quiz application

In this 5-lesson project you'll build a quiz application. Each lesson adds one piece, and by the final lesson you'll have a working program.

You'll use the class, constructor, encapsulation and constant concepts you learned in previous groups. Throughout the project you'll define Question and Quiz classes. In the first lesson you'll create the Question class: question text and answer fields, a constructor and a toString method.

The Question class skeleton

The first lesson defines the Question class. The class will have a question text and an answer field. The constructor takes both fields as parameters. A toString method shows the question readably.

Example skeleton: class Question { String text; String answer; Question(String t, String a) { text = t; answer = a; } public String toString() { return text + " = " + answer; } }. This class forms the foundation for later lessons. In the second lesson a Quiz class will collect these questions in an array. The toString method shows the question and answer on one line; this is useful when the quiz is played.

Practice Define the Question class

Define a class Question. Add String text and String answer fields. Write a Question(String t, String a) constructor; assign both fields. Add a public String toString() method returning text + " = " + answer. In main create a Question instance and print it with println.

Starter code

Main.java
// Define the Question class
// Add text and answer fields, constructor and toString
// Instantiate and print in main

Sample solution

Main.java
class Question {
    String text;
    String answer;
    Question(String t, String a) {
        text = t;
        answer = a;
    }
    public String toString() {
        return text + " = " + answer;
    }
    public static void main(String[] args) {
        Question q = new Question("Capital", "Paris");
        System.out.println(q);
    }
}

Expected output

Capital = Paris

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which class is defined in the first lesson of the quiz project?

  • Score
  • Question Correct answer
  • Answer
  • Quiz

Explanation: The first lesson creates the Question class.

2 Complete the Question constructor

Question
class Question {
    String text;
    String answer;
    ____(String t, String a) {
        text = t;
        answer = a;
    }
}
Answer
class Question {
    String text;
    String answer;
    Question(String t, String a) {
        text = t;
        answer = a;
    }
}

Explanation: The constructor name must match the class name.

3 Match the Question parts

Term Meaning
String text Question text
String answer Answer
Question(String t, String a) Constructor
text + answer toString body

All lessons in Intermediate