w3resource

Kotlin program: User input and display


Write a Kotlin program to take user input and display it.


Pre-Knowledge (Before you start!)

  • Basic Kotlin Syntax.
  • Kotlin Functions.
  • Command-Line Arguments.
  • Conditional Statements.
  • String Interpolation.
  • Printing Output.
  • Error Handling.

Hints (Try before looking at the solution!)

  • Define the main() Function.
  • Check for Input.
  • Retrieve User Input.
  • Display the Input.
  • Handle Missing Input.
  • Run the Program.
  • Common Errors to Avoid:
    • Forgetting to check if args is empty.
    • Misplacing quotes or parentheses in string interpolation.
    • Not providing command-line arguments.

Sample Solution:

Kotlin Code:

fun main(args: Array) {
    if (args.isNotEmpty()) {
        val name = args[0]
        println("Entered name: $name")
    } else {
        println("No name provided. Please provide a name as a command-line argument.")
    }
} 

Sample Output:

Entered name: Virginia

Explanation:

In the above exercise, the readLine() function is used to read the user input from the console. The input is then stored in the name variable. Finally, the program displays the entered name using string interpolation.

Kotlin Editor:


Previous: Display current date and time.
Next: Arithmetic operations on two numbers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.