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.
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:
println()statement to prompt the user with a question to answer
- The name of our immutable variable,
- The assignment operator,
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
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:
- Click the Run button when the code is complete
- Use the following command in the terminal:
kotlinc myCode.kt -include-runtime -d myCode.jar
- 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.
The first step in gathering input is to create a variable that will store the input from the user.
println() statement in the editor, declare the variable
myName and assign it the value
Click Run to save your work. Remember there will be no output yet.
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
-d as discussed above.
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.