Java
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.
Exercise 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.
Show example solution
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);
}
}
Test yourself
-
Which class is defined in the first lesson of the quiz project?
Show answer
Question — The first lesson creates the Question class.
-
Complete the Question constructor
class Question {
String text;
String answer;
____(String t, String a) {
text = t;
answer = a;
}
}
Show answer
class Question {
String text;
String answer;
Question(String t, String a) {
text = t;
answer = a;
}
}
-
Match the Question parts
- String text
- Question text
- String answer
- Answer
- Question(String t, String a)
- Constructor
- text + answer
- toString body
Next lesson: Adding questions