Kotlin
Running the quiz
Learn to ask questions in turn with the runQuiz function.
Running the quiz
In the third lesson we add the runQuiz function. It prints all questions in the list in order.
Example: fun runQuiz() { for (q in questions) { println(q.text); println("Answer: ${q.answer}") } }. With for (q in questions) each question is visited in order. q.text and q.answer access the question's fields. The data model comes from the first lesson and addQuestion from the second. This lesson only adds the runQuiz function.
Printing question and answer
runQuiz prints two lines per question: first the question text, then the correct answer.
Example: for (q in questions) { println(q.text); println("Answer: ${q.answer}") }. q.text gives the question text, q.answer the correct answer. ${q.answer} embeds the property inside a string template. The call is runQuiz(). Questions must be added before with addQuestion; otherwise runQuiz prints nothing.
Exercise Print questions with runQuiz
Build on the previous lessons' solution: data class Question(val text: String, val answer: String), val questions: MutableList<Question> = mutableListOf() and fun addQuestion(text: String, answer: String) are defined. Add a fun runQuiz() function whose body iterates each question with for (q in questions) and prints println(q.text) and println("Answer: ${q.answer}"). In main add two questions and call runQuiz().
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 main() {
addQuestion("Capital city?", "Ankara")
addQuestion("2+2?", "4")
runQuiz()
}
Test yourself
-
What does the <code>runQuiz</code> function use to iterate over questions?
List iteration in Kotlin is done with for (element in list).
- while and index
- do-while
- recursion
- for (q in questions)
Show answer
for (q in questions) — for (q in questions) iterates over each question in order.
-
Match the runQuiz parts
- fun runQuiz()
- Function signature
- for (q in questions)
- List loop
- q.text
- Question text
- q.answer
- Correct answer
-
Complete the runQuiz loop
fun runQuiz() {
for (q in ____) {
println(q.text)
println("Answer: ${q.answer}")
}
}
Show answer
fun runQuiz() {
for (q in questions) {
println(q.text)
println("Answer: ${q.answer}")
}
}
Next lesson: Score calculation