Dart
Running the quiz
Learn to ask questions in turn with the run method.
The play method
To run the quiz we write a play method. It prints each question in the list with a number. A for loop iterates the list.
Example: void play() { for (var i = 0; i < questions.length; i++) { print('${i + 1}. ${questions[i].text}'); } }. Here i starts at zero and goes up to questions.length. questions[i] accesses the i-th question.
${i + 1} is string interpolation; it gives the question number. ${questions[i].text} is the question text.
Numbered list output
When play is called each question is printed as 1. What is the capital?. The expression ${i + 1} turns the zero-based index into a one-based number.
With two questions the output is: 1. What is the capital? and 2. How many days in a week?. Each question appears on its own line.
This structure is the foundation of real quiz apps: showing questions in order. The next lesson teaches how to evaluate answers.
Exercise Add the play method
Add a void play() method to the Quiz class. The method loops over the questions list with a for loop and prints each question as ${i + 1}. ${questions[i].text}. The main already adds two questions; add the quiz.play() call.
Show example solution
class Question {
String text;
String answer;
Question(this.text, this.answer);
}
class Quiz {
List<Question> questions = [];
void addQuestion(Question q) {
questions.add(q);
}
void play() {
for (var i = 0; i < questions.length; i++) {
print('${i + 1}. ${questions[i].text}');
}
}
}
void main() {
var quiz = Quiz();
quiz.addQuestion(Question('What is the capital?', 'Ankara'));
quiz.addQuestion(Question('How many days in a week?', '7'));
quiz.play();
}
Test yourself
-
The for loop condition
void play() {
for (var i = 0; i < ____.length; i++) {
print('${i + 1}. ${questions[i].text}');
}
}
Show answer
void play() {
for (var i = 0; i < questions.length; i++) {
print('${i + 1}. ${questions[i].text}');
}
}
-
Match the loop parts
- var i = 0
- Start
- i < questions.length
- Condition
- i++
- Increment
- questions[i].text
- Question text
-
What does questions[i] give?
var q = questions[i];
- The number of questions
- The i-th Question object
- A list
- A number
Show answer
The i-th Question object — questions[i] gives the i-th Question object in the list.
Next lesson: Score calculation