In this Kotlin tutorial we cover how to take inputs from console and print them. To take user inputs from console we will use readline() method and Scanner class.
Let's write code to take user inputs
Using ReadLine method
import java.util.Scanner fun main() { print("Enter text: ") var inputtext = readLine() print("You entered: $inputtext") } |
output:
Enter text: Welcome to Kotlin Console input |
Output 2:
Enter text: 123 Text number true boolean |
Using Scanner class
To read inputs using scanner we need to import java.util.Scanner package.
Let's write example which will ask user to enter integer,float and boolean values
import java.util.Scanner fun main() { // create an object for scanner class val integer = Scanner(System.`in`) print("Enter an integer: ") // nextInt() method is used to take // next integer value and store in enteredinteger variable var enteredinteger:Int = integer.nextInt() println("You entered: $enteredinteger") val floatvalues = Scanner(System.`in`) print("Enter a float value: ") // nextFloat() method is used to take next // Float value and store in enteredfloatvalues variable var enteredfloatvalues:Float = floatvalues.nextFloat() println("You entered: $enteredfloatvalues") val booleanValue = Scanner(System.`in`) print("Enter a boolean: ") // nextBoolean() method is used to take // next boolean value and store in enteredBoolean variable var enteredBoolean:Boolean = booleanValue.nextBoolean() println("You entered: $enteredBoolean") }
|
Output:
Enter an integer: 12 Process finished with exit code 0
|
Suppose if i enter float value instead of Integer on the first argument it will through InputMismatchException error
Enter an integer: 1.2 |
Conclusion: In this kotlin example we covered how to read user inputs from the console and alos learned what is InputMismatchException is exception error
Article Contributed By :
|
|
|
|
1037 Views |