Skip to Content
Learn
Using Text Variables
User Input

User input is an important part of computer applications. To unlock our phones we enter a code. When shopping online we give our payment information. Our input helps the operation of many applications we use every day.

The readLine() function in Kotlin is used to tell the program to pause until some type of input is given by the user. Once the Enter key is pressed, anything typed into the console is returned by the readLine() function as a String. We can then save the input to a variable. Let’s take a look at readLine() in action:

println("Please enter your favorite color.") val myColor = readLine()

The two statements above can be broken into 4 parts:

  1. A println() statement to prompt the user with a question to answer
  2. The name of our immutable variable, myColor
  3. The assignment operator, =
  4. The readLine() function

The program will prompt the user with a question, accept their input with the readLine() function and return the String input once the Enter key is pressed. The returned String will initialize the declared variable myColor.

We can now use a String template to output the user input contained in the variable:

println("Your favorite color is $myColor")

Before we continue, let’s note a change to our current environment. In order to work with user input, the output terminal on the right side of our screen has been changed to a terminal running the Bash shell. We use this new terminal to type input into our program as well as use it to compile and run our program.

In order to run our program in this exercise we will follow these 3 steps:

  1. Click the Run button when the code is complete
  2. Use the following command in the terminal:
kotlinc myCode.kt -include-runtime -d myCode.jar
  1. Followed by this final command:
java -jar myCode.jar

The first step ensures the Kotlin file is saved. The second step compiles the Kotlin file, myCode.kt, into bytecode and saves it in a .jar file. The third step runs the compiled application. This process is described in more detail in this Kotlin Tutorial.

Instructions

1.

The first step in gathering input is to create a variable that will store the input from the user.

After the println() statement in the editor, declare the variable myName and assign it the value readLine().

Click Run to save your work. Remember there will be no output yet.

2.

Now it’s time to compile the code.

In the terminal, use kotlinc to compile UserInput.kt to UserInput.jar.

Be sure to use the complete command with the options -include-runtime and -d as discussed above.

3.

Great work! One more step. Using the java command with the -jar flag, run the compiled code using the UserInput.jar file.

Once it runs, you will be prompted to type your name. Type your response and hit Enter. You should then see the output from line 6.

Folder Icon

Take this course for free

Already have an account?