Java
Adding questions
Add questions with addQuestion.
Adding questions
The second lesson defines the Quiz class. The quiz holds questions in an array. An add method adds new questions; a count field tracks how many questions exist.
Example: class Quiz { Question[] questions; int count; Quiz() { questions = new Question[10]; count = 0; } void add(Question q) { questions[count] = q; count++; } }. Here the questions array has a capacity of 10. The add method adds one question each call and increments count. This structure stores questions in order. To avoid exceeding array bounds, count is checked; we keep it simple for now.
Storing questions in an array
The Quiz class stores questions in a Question[] array. An array is a fixed-size data structure; its capacity is specified when created. The add method places the question at the next empty slot.
Example: questions = new Question[10]; creates an array of 10 elements. questions[0] holds the first question, questions[1] the second. The count variable indicates the next empty index. When add is called, questions[count] = q; adds the question and count is incremented. This is a simple but effective storage method. When the array is full, no more additions are made; we do not hit this limit for now.
Exercise Add the Quiz class
Add a Quiz class to the file. Write Question[] questions and int count fields. In the Quiz() constructor create the array with new Question[10], set count = 0. Add a void add(Question q) method; run questions[count] = q; and count++. Put main inside Quiz; create a Quiz instance, add two questions and print count.
Show example solution
class Question {
String text;
String answer;
Question(String t, String a) {
text = t;
answer = a;
}
public String toString() {
return text + " = " + answer;
}
}
class Quiz {
Question[] questions;
int count;
Quiz() {
questions = new Question[10];
count = 0;
}
void add(Question q) {
questions[count] = q;
count++;
}
public static void main(String[] args) {
Quiz quiz = new Quiz();
quiz.add(new Question("Capital", "Paris"));
quiz.add(new Question("City", "London"));
System.out.println(quiz.count);
}
}
Test yourself
-
Match the Quiz parts
- Question[] questions
- Question array
- int count
- Question count
- void add(Question q)
- Add method
- count++
- Increment counter
-
What does the count field track in the Quiz class?
- The score
- The array size
- The quiz duration
- The question count
Show answer
The question count — The question count — count holds how many questions are added.
-
Complete the add method
void add(Question q) {
questions[count] = q;
____;
}
Show answer
void add(Question q) {
questions[count] = q;
count++;
}
Next lesson: Running the quiz