Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn kotlin Quiz


Sure, let's create a simple Kotlin quiz example where the user is asked multiple-choice questions and receives feedback on their answers. Here's how we can do it:

Example

import kotlin.system.exitProcess

data class Question(val prompt: String, val options: List<String>, val correctAnswer: Int)

fun displayQuestion(question: Question) {
println(question.prompt)
question.options.forEachIndexed { index, option ->
println("${index + 1}. $option")
}
}

fun getUserAnswer(): Int {
print("Your answer: ")
return readLine()?.toIntOrNull() ?: 0
}

fun evaluateAnswer(question: Question, userAnswer: Int): Boolean {
return userAnswer == question.correctAnswer
}

fun main() {
val questions = listOf(
Question(
"What is the capital of France?",
listOf("London", "Paris", "Berlin", "Rome"),
2
),
Question(
"Which planet is known as the Red Planet?",
listOf("Venus", "Mars", "Jupiter", "Saturn"),
2
),
Question(
"What is the largest mammal?",
listOf("Elephant", "Blue whale", "Giraffe", "Hippopotamus"),
2
)
)

var score = 0
for (question in questions) {
displayQuestion(question)
val userAnswer = getUserAnswer()

if (evaluateAnswer(question, userAnswer)) {
println("Correct!")
score++
} else {
println("Incorrect! The correct answer was: ${question.options[question.correctAnswer - 1]}")
}

println()
}

println("Quiz complete!")
println("Your final score is: $score/${questions.size}")
if (score == questions.size) {
println("Congratulations! You got all the questions correct.")
} else {
println("Better luck next time!")
}
}

This program defines a Question class to represent each question in the quiz. Each question has a prompt, a list of options, and the index of the correct answer. The main function then creates a list of questions, asks the user each question, evaluates their answers, and keeps track of their score.

Here's a breakdown of the key functions:

When you run this program, it will ask the user each question, provide feedback on their answers, and finally display their score at the end of the quiz.

Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java