Learn how to create a simple text menu in Kotlin using the when statement and console input handling for beginner-friendly programming.
fun main() {
// Variable to store the user's choice
var scelta: Int?
do {
// Print the menu
println("\nMain menu:")
println("1. Greet")
println("2. Show date")
println("3. Calculate sum")
println("4. Exit")
print("Enter your choice (1-4): ")
// Read input from console and convert to Int (null if invalid)
scelta = readLine()?.toIntOrNull()
when (scelta) {
1 -> {
// Case 1: greeting
println("Hello! Welcome to the program.")
}
2 -> {
// Case 2: show current date
val dataCorrente = java.time.LocalDate.now()
println("Today's date: $dataCorrente")
}
3 -> {
// Case 3: calculate sum of two numbers entered by the user
print("Enter the first number: ")
val num1 = readLine()?.toIntOrNull()
print("Enter the second number: ")
val num2 = readLine()?.toIntOrNull()
if (num1 != null && num2 != null) {
val somma = num1 + num2
println("The sum of $num1 and $num2 is $somma")
} else {
println("Invalid input. Please enter integer numbers.")
}
}
4 -> {
// Case 4: exit the program
println("Exiting the program. Goodbye!")
}
else -> {
// Default case: invalid input
println("Invalid choice. Please enter a number from 1 to 4.")
}
}
} while (scelta != 4) // Repeat until exit is chosen
}Kotlin standard library
Console input via readLine()
No external dependencies
CONFIG: no external configuration needed