Dart
Score calculation
Learn correct count with the score calculation method.
Score tracking
To evaluate the quiz we write a grade method. It compares a given answer list with the question answers and writes the correct count to the score field. Then it prints the score.
The Quiz class gets an int score = 0; field. The grade(List<String> answers) method compares each answer with questions[i].answer; if equal it runs score++.
This structure is the basis of automatic answer evaluation. Real apps read answers from the user; here we simulate with a fixed list.
Showing the result
After the loop the grade method prints the result with print('Score: $score'). If one of two answers is correct the output is Score: 1.
$score is string interpolation; it embeds the score variable value into the text. In Dart $variable gives the variable value.
When this method is called the quiz is evaluated. The next lesson combines all pieces into a working app.
Exercise Add the grade method and score field
Add an int score = 0 field to the Quiz class. Then write void grade(List<String> answers): start with score = 0, loop with for to compare each answer with questions[i].answer, run score++ on a match. After the loop write print('Score: $score'). The main already calls 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.grade(['Ankara', 'Wrong']);
}
Test yourself
-
Match the score parts
- int score = 0
- Score field
- grade(List<String> answers)
- Grading method
- answers[i] == questions[i].answer
- Comparison
- score++
- Correct count increment
-
When is answers[i] == questions[i].answer true?
if (answers[i] == questions[i].answer) {
score++;
}
- When the answer is empty
- When the answer is wrong
- When the given answer matches the correct one
- As many times as questions
Show answer
When the given answer matches the correct one — the condition holds when the given answer equals the correct one.
-
Score increment
void grade(List<String> answers) {
score = 0;
for (var i = 0; i < questions.length; i++) {
if (answers[i] == questions[i].answer) {
____;
}
}
print('Score: $score');
}
Show answer
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');
}
Next lesson: Putting it together