Java
Running the quiz
Ask questions in turn with run.
Playing the quiz
The third lesson adds a method that plays the quiz. A display method prints all added questions in order. A for loop iterates through the questions in the array.
Example: void display() { for (int i = 0; i < count; i++) { System.out.println(questions[i]); } }. This method prints count questions. questions[i] represents each question; println automatically calls toString. This lets you see the quiz's contents. Later, answer checking will be added to this structure; for now, displaying the questions is enough.
Iterating with a loop
A for loop is used to iterate through an array. The loop variable i starts at zero and increments up to count. Each step accesses one question via questions[i].
Example: for (int i = 0; i < count; i++) { System.out.println(questions[i]); }. Here i starts at zero and increments by one each loop. The loop continues as long as i < count. Questions are accessed in order as questions[0], questions[1]. This is the basic method of iterating arrays. You use this structure when you want to do the same operation for all elements of an array.
Exercise Add a display method to Quiz
Add a void display() method to the Quiz class. In its body, loop with i from zero to count; at each step run System.out.println(questions[i]);. In main create a Quiz instance, add two questions and call display().
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++;
}
void display() {
for (int i = 0; i < count; i++) {
System.out.println(questions[i]);
}
}
public static void main(String[] args) {
Quiz quiz = new Quiz();
quiz.add(new Question("Capital", "Paris"));
quiz.add(new Question("City", "London"));
quiz.display();
}
}
Test yourself
-
How many questions does the display method print?
- The entire array
- Up to count
- 1 question
- 10 questions
Show answer
Up to count — The display method prints up to count questions.
-
Complete the for loop condition
for (int i = 0; i < ____; i++) {
System.out.println(questions[i]);
}
Show answer
for (int i = 0; i < count; i++) {
System.out.println(questions[i]);
}
-
Match the loop parts
- int i = 0
- Start
- i < count
- Condition
- i++
- Increment
- questions[i]
- Access
Next lesson: Score calculation