Dart
Putting it together
Combine the Quiz class with a menu loop.
Integration
Now it is time to combine all pieces. The Question class, the Quiz class, addQuestion, play and grade methods are ready. What remains is to create the quiz in main, add questions, play and grade.
The running session goes like this: create a quiz, add two questions, show them with play(), evaluate answers with grade(). The output includes both questions and the score.
This shows how an object-oriented app is built piece by piece. Each lesson added a brick; now the building is complete.
Running session
All classes are defined. In main create a quiz, add two questions, call play() and grade(). The output shows numbered questions first, then the score.
With two questions and the answer list ['Ankara', 'Wrong'] the output is: 1. What is the capital?, 2. How many days in a week?, Score: 1. One answer is correct, one is wrong.
The project is complete! You used OOP, lists, loops and conditions together. You can extend this structure to build bigger quiz apps.
Exercise Working quiz
All classes are defined (Question, Quiz, addQuestion, play, grade). In main create a Quiz, add two questions ('What is the capital?', 'Ankara' and 'How many days in a week?', '7'), call quiz.play() and quiz.grade(['Ankara', 'Wrong']).
Show example solution
class Question {
String text;
String answer;
Question(this.text, this.answer);
}
class Quiz {
List<Question> questions = [];
int score = 0;
void addQuestion(Question q) {
questions.add(q);
}
void play() {
for (var i = 0; i < questions.length; i++) {
print('${i + 1}. ${questions[i].text}');
}
}
void grade(List<String> answers) {
score = 0;
for (var i = 0; i < questions.length; i++) {
if (answers[i] == questions[i].answer) {
score++;
}
}
print('Score: $score');
}
}
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();
quiz.grade(['Ankara', 'Wrong']);
}
Test yourself
-
Which order makes sense?
- grade, play, addQuestion
- addQuestion, grade, play
- play, addQuestion, grade
- addQuestion, play, grade
Show answer
addQuestion, play, grade — first questions are added, then played, finally graded.
-
Match methods to their purpose
- addQuestion
- Add a question
- play
- Show questions
- grade
- Evaluate answers
- questions.length
- Question count
-
Add the second question
void main() {
var quiz = Quiz();
quiz.addQuestion(Question('What is the capital?', 'Ankara'));
____.addQuestion(Question('How many days in a week?', '7'));
quiz.play();
quiz.grade(['Ankara', 'Wrong']);
}
Show answer
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();
quiz.grade(['Ankara', 'Wrong']);
}
Next lesson: List