Simple Text Menu with when in Kotlin

Learn how to create a simple text menu in Kotlin using the when statement and console input handling for beginner-friendly programming.

Brief Introduction

Simple Text Menu with when in Kotlin (kotlin)
DESCRIPTION:
Basic example of a text menu in Kotlin using the when statement to handle user choices. The program displays a menu, reads input from the console, and prints a message based on the selected option. Useful to understand the when control structure and keyboard input handling.

ADDITIONAL NOTES:
The program is designed to be simple and educational, suitable for beginners who want to learn how to use when and handle console input in Kotlin.

EXPLANATIONS:
- Use of readLine() to read keyboard input as a string.
- Conversion of input to Int with toIntOrNull() to avoid crashes in case of non-numeric input.
- when structure to handle different menu cases clearly and readably.
- Use of a while loop to repeat the menu until the user chooses to exit (option 4).

Example Code: kotlin

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
}
×
×
×
Do you want to regenerate the answer?
×
Export chat
Choose export format
Generazione PDF in corso…
Allegati
×
You are about to close the chat and switch to the image generator. If you are not logged in, you will lose our chat. Do you confirm?
You are viewing a shared chat in temporary mode. It will not be saved.
×
Saved prompts
×
Private note
×
Label
×
Search all chats
×
Your insights
Analyzing…
×
AI Preferences
Assistant name 30
Answer length
AI model
Structured answers
Include examples
Use emojis
Guide me, don't solve Hints and questions instead of a ready answer
More settings →
×
Share this chat
Anyone opening this link can view the chat or add it to their profile as their own chat.
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
Shared chat
Someone shared a chat with you. Do you want to just view it or add it to your chats?
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
×

Saved messages

Loading...

×

Chat History

example-programs · CHAT HISTORY

Loading...

AI Preferences

×
  • BasicQuick and essential answers for study
  • MediumHigher quality for study and programming
  • AdvancedComplex reasoning and detailed analysis
Explain Steps

What do you need?

Kotlin standard library

Console input via readLine()

No external dependencies

CONFIG: no external configuration needed

Similar Topics

Kotlin Hello World from Command Line
Basic Kotlin Hello World program example run from the command line to learn syntax and verify environment setup with minimal code.
Sum Calculator of Two Numbers in Kotlin
Simple Kotlin program that reads two integers, calculates their sum, and prints the result. Perfect for beginners learning Kotlin input and arithmetic.
Printing a List of Names with a for Loop in Kotlin
Learn how to print a list of names using a for loop in Kotlin with simple code ideal for beginners to understand iteration and basic syntax.
Conversion from Celsius to Fahrenheit in Kotlin
Simple Kotlin program converting Celsius to Fahrenheit with input validation and formatted output, ideal for beginners learning Kotlin programming basics.
Check Even or Odd Number in Kotlin
Learn how to check if a number is even or odd in Kotlin using console input, modulo operation, and input validation with a simple Kotlin program.
Mini Kotlin program to calculate age from birth year
Simple Kotlin program to calculate age from birth year using java.time.Year and console input with validation for accurate age calculation.
Personalized Welcome Message Generator in Kotlin
A simple Kotlin program that generates personalized welcome messages by requesting user input and handling empty names with default greetings.
Count characters in a string in Kotlin
Complete Kotlin example to count characters in a user input string via console using readLine and length property with no external dependencies.