CodeGym /Courses /Kotlin SELF /Keyboard input

Keyboard input

Kotlin SELF
Level 2, Lesson 5
Available

1. Reading from the console, standard input

In previous lectures, we got familiar with commands for printing to the screen. For that, we used the print() and println() functions. Simple and convenient.

But, as you probably already suspect, printing to the screen alone is not enough. The goal of most programs is to do something useful for the user. That’s why very often you need the user to be able to enter data from the keyboard.

In Kotlin, there are 2 functions for reading input from the keyboard:

  • readln() — returns a String (or throws an error)
  • readLine() — returns a String or null

We’ll start with the simpler option — readln(). Once we cover working with null in Kotlin, you’ll be able to try the other options too.

2. The readln() function

The readln() function can read one line from standard input (that is, from the keyboard). Usually it looks like this:

Code Explanation
val name = readln()
Read a text line.
val age = readln().toInt()
Then read one more line and convert it to a number (Int).

It doesn’t look hard, but is it really that simple? I think you have a bunch of questions, and we’ll answer them now. But first, let’s demonstrate an example of a complete program that uses readln():

fun main() {
    val name = readln()
    val age = readln().toInt()

    println("Name: " + name)
    println("Age: " + age)
}

3. Declaring variables and reading data

The first question: what are these lines val name = readln() and val age = readln().toInt()?

As you (hopefully) already remember, in Kotlin variables are usually declared using val (immutable) or var (mutable). Reading a line works the same way:

val name = readln()
Declaring and initializing a variable by reading from the console

Everything on the left side of the equals sign is a variable declaration with the name name. You could have named it, for example, s or userName, or even keyboardInput. Then the code would look like this:

val s = readln()
val userName = readln()
val keyboardInput = readln()

I think now everything has become much clearer. And the code on the right side of the equals sign doesn’t contain anything complicated either:

  • readln() — reads a line from the console;
  • .toInt() — tries to convert the string to an integer.

After these lines are executed, we’ll have variables that our program can use to work with the data entered by the user.

4. Reading input from the console

Entering data from the keyboard using readln() is very easy.

To read a line from the keyboard, you need the command:

val str = readln()

When the program reaches this line, it will pause and wait until the user enters input and presses the Enter key. After that, everything the user typed will be saved into the str variable.

To read a number from the keyboard, they usually do this:

val number = readln().toInt()

Everything here is analogous to the previous command. When the program reaches this line, it will pause and wait until the user enters input and presses the Enter key. After that, everything the user typed will be converted to a number and stored in the number variable.

If the user entered data that cannot be converted to an integer, an error will occur in the program (usually NumberFormatException), and it will terminate.

To read a floating-point number from the keyboard, you need the command:

val number = readln().toDouble()

This command is completely analogous to toInt(), except it converts the string to a Double.

An example program that reads two numbers from the keyboard and prints their sum:

fun main() {
    val a = readln().toInt()
    val b = readln().toInt()

    println(a + b)
}

5. trim(): what it does and why it’s needed

trim() is a function on String that removes whitespace characters at the edges of a string: on the left and on the right. Imagine a string as a doormat at the entrance, and spaces as dirt on your shoes. trim() is like quickly “wiping off your shoes” so you don’t spread mess around the house (that is, around your code).

The main advantage of trim() is that it’s a very cheap action for a programmer’s brain: one function call—and you’ve already protected yourself from half of the “why won’t it parse?!” cases. It’s especially useful before toInt()/toIntOrNull(), because the string " 42 " looks like a number, but for the parser it’s no longer a “clean” format.

We’re not reading input from the console yet (that will be the next lecture), so we’ll imitate “raw input” using regular string literals.

fun main() {
    val raw = "   42   "
    val cleaned = raw.trim()

    println("raw='$raw'")         // raw='   42   '
    println("cleaned='$cleaned'") // cleaned='42'
}

Notice the trick with quotes: when we print a string as '$raw', spaces become visible; otherwise you’ll just see “42” and think there are no spaces (but they’re there, quietly sitting and grinning).

trim() is not magic: what it does not do

Beginners often have a natural dream: “I’ll just do trim() and the string will become perfect.” But trim() is not a deep clean of the whole apartment—it’s just “sweeping the doorstep.” It does not remove spaces inside the string, because sometimes those spaces are part of the meaning: "Hello world" must not turn into "Helloworld".

This is very important; otherwise you can accidentally corrupt data. For example, the name "Ada Lovelace" with a space in the middle is a normal name, and removing the space would break reality (and reality is fragile enough as it is).

Let’s look at an example where the inner space remains:

fun main() {
    val raw = "  10 20  "
    val cleaned = raw.trim()

    println("raw='$raw'")         // raw='  10 20  '
    println("cleaned='$cleaned'") // cleaned='10 20'
}

See? The edges were cleaned, the middle stayed. And that’s correct.

6. Input/output scenarios

Scenario 1: “Polite introduction”

Let’s make the friendliest scenario: the program asks for a name and age (for now, age can be left as text so we don’t complicate things), and then prints a message.

A useful habit here: each input goes into a separate variable. Don’t try to “read twice and forget,” or you’ll lose the thread of the conversation yourself.

fun main() {
    print("How should I address you? ")
    val name = readln().trim()

    print("How old are you (text is fine)? ")
    val ageText = readln().trim()

    println("Hi, $name! You are '$ageText' — sounds solid.")
    // for example: Hi, Ada! You are '20' — sounds solid.
}

Why is trim() useful here even for a name? Because people sometimes enter an accidental trailing space (especially on a phone), and then the name becomes "Ada "—which will look odd in the output.

Scenario 2: “Mini calculator”

Let’s assemble a small program that asks for two integers and prints the results of several operations. There’s a nuance here: if we use toInt(), the program can crash on bad input; if we use toIntOrNull(), we’ll get null, but we won’t be able to compute normally without additional topics (branching, error handling). So we’ll make two versions: a “strict” one and an “observant” one.

Strict version

Here we bet on the user being disciplined. That’s fine for a learning example: you’ll see what the “happy path” looks like.

fun main() {
    print("a: ")
    val a = readln().trim().toInt()

    print("b: ")
    val b = readln().trim().toInt()

    println("a + b = ${a + b}") // for example: a + b = 13
    println("a - b = ${a - b}")
    println("a * b = ${a * b}")
}

An important note: division / and remainder % are things we technically can do, but division by zero “breaks” execution. We don’t yet know how to protect against that nicely without future tools, so in today’s lecture it’s better not to provoke a / b in interactive input.

Observant version

Now let’s make a version that doesn’t crash on bad input and helps you understand what actually came from input.

fun main() {
    print("Enter a: ")
    val aText = readln()
    val a: Int? = aText.trim().toIntOrNull()

    print("Enter b: ")
    val bText = readln()
    val b: Int? = bText.trim().toIntOrNull()

    println("aText='$aText' -> a=$a") // for example: aText=' 7 ' -> a=7
    println("bText='$bText' -> b=$b") // for example: bText='q' -> b=null
}

This looks “boring” because we’re not calculating. But pedagogically it’s an honest step: you’re learning to design input so that the program is predictable and doesn’t turn into a lottery of “will it crash or won’t it.”

Scenario 3: “Cafeteria checkout”

Let’s build a mini app that already resembles a real task: there’s a product (text), there’s a price and quantity (numbers), and you need to output the total.

To avoid getting stuck on error handling, we’ll take the strict path (toInt()), but we’ll be disciplined with trim() and careful with output via templates.

fun main() {
    print("Product name: ")
    val title = readln().trim()

    print("Price (integer): ")
    val price = readln().trim().toInt()

    print("Quantity (integer): ")
    val qty = readln().trim().toInt()

    val total = price * qty
    println("Item: $title")                 // for example: Item: Bun
    println("Total: $qty * $price = $total") // Total: 2 * 35 = 70
}

Here you use almost everything from earlier:

  • a string comes in via readln();
  • we normalize it with trim();
  • we get numbers with toInt();
  • we compute using Int (*);
  • we output via templates ${...}.

7. Input debugging and a cheat sheet

Observable input: spaces, quotes, and string length

Sometimes a program “doesn’t work,” but in reality you just don’t see what exactly came in as input. Spaces are champions of stealth: they exist, but you can’t see them. That’s why in learning examples it’s useful to print strings in quotes and sometimes show length.

fun main() {
    print("Enter something (I’ll show the length): ")
    val raw = readln()
    val cleaned = raw.trim()

    println("raw='$raw' (len=${raw.length})")
    println("cleaned='$cleaned' (len=${cleaned.length})")
}

If you enter three spaces and press Enter, then raw.length will be 3, and cleaned.length will become 0. That’s direct proof that trim() removes spaces at the edges.

Function cheat sheet

Sometimes it’s useful to assemble a “card” of tools so your brain doesn’t have to keep everything in a fog.

Tool What it does What it returns
print("...")
prints without a newline (handy for a prompt)
Unit
println("...")
prints with a newline
Unit
readln()
reads a single line up to Enter
String
trim()
removes spaces at the edges of a string
String
toInt()
strictly parses a string as an Int
Int
(or an error at runtime)
toIntOrNull()
tries to parse a string as an Int
Int?
(a number or null)
"x = $x, sum=${a+b}"
inserts values into text (templates)
String
1
Task
Kotlin SELF, level 2, lesson 5
Locked
Chat with a bot
Chat with a bot
1
Task
Kotlin SELF, level 2, lesson 5
Locked
Input magnifier
Input magnifier
1
Task
Kotlin SELF, level 2, lesson 5
Locked
Elevator number
Elevator number
1
Task
Kotlin SELF, level 2, lesson 5
Locked
Parsing log
Parsing log
1
Survey/quiz
Integers, strings, and input, level 2, lesson 5
Unavailable
Integers, strings, and input
Integers, strings, and input
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION