Kotlin
Score calculation
Learn correct count with the score calculation function.
Score calculation
In the fourth lesson we add the score function. It takes a list of answers, compares each with the correct answer, and returns the count of correct ones.
Example: fun score(answers: List<String>): Int { var correct = 0; for (i in questions.indices) { if (questions[i].answer == answers[i]) correct++ }; return correct }. questions.indices gives the range of indices in the list. questions[i].answer accesses the i-th question's answer. answers[i] is compared with the user's i-th answer. Correct matches are counted in correct.
A score calculation example
The score function takes a List<String>. For each question it compares the user's answer with the correct answer.
Example: with two questions added, calling score(listOf("Ankara", "5")) gives 1 because the first is correct and the second is wrong. The counter starts with var correct = 0. Inside the loop each match increments with correct++. Finally return correct returns the value. This function is used to show the score at the end of the quiz.
Exercise Add the score function
Build on the previous lessons' solution: data class Question(val text: String, val answer: String), val questions: MutableList<Question> = mutableListOf(), fun addQuestion(text: String, answer: String) and fun runQuiz() are defined. Add a fun score(answers: List<String>): Int function whose body starts with var correct = 0, iterates each question with for (i in questions.indices), does if (questions[i].answer == answers[i]) correct++, and returns return correct. In main add two questions and print the result with println(score(listOf("Ankara", "5"))).
Show example solution
data class Question(val text: String, val answer: String)
val questions: MutableList<Question> = mutableListOf()
fun addQuestion(text: String, answer: String) {
questions.add(Question(text, answer))
}
fun runQuiz() {
for (q in questions) {
println(q.text)
println("Answer: ${q.answer}")
}
}
fun score(answers: List<String>): Int {
var correct = 0
for (i in questions.indices) {
if (questions[i].answer == answers[i]) correct++
}
return correct
}
fun main() {
addQuestion("Capital city?", "Ankara")
addQuestion("2+2?", "4")
println(score(listOf("Ankara", "5")))
}
Test yourself
-
Match the score parts
- fun score(answers)
- Function signature
- questions.indices
- Index range
- var correct = 0
- Counter
- correct++
- Increment
-
What does <code>questions.indices</code> return?
- An index range (0..size-1)
- A new list
- A Boolean result
- The items of the list
Show answer
An index range (0..size-1) — questions.indices is the index range from 0 to size-1.
-
Complete the score comparison
if (questions[i].answer == ____) correct++
Show answer
if (questions[i].answer == answers[i]) correct++
Next lesson: Putting it together