Definition
- Kotlin uses java.util.Scanner class to scan user inputs.
- To read a string, nextLine() method is used.
- Similarly, it has methods like nextInt(), nextLong() methods to get inputs of corresponding types.
Scanner Methods
Scanner scanner_variable = Scanner(System.`in`)
//Reading Int input
scanner_variable.nextInt()
//Reading Float Input
scanner_variable.nextFloat()
//Reading Double Input
scanner_variable.nextDouble()
//Reading Boolean Input
scanner_variable.nextBoolean()
//Reading Short Input
scanner_variable.nextShort()
//Reading Long Input
scanner_variable.nextLong()
//Reading String Input
scanner_variable.nextLine()
Syntax
Scanner scanner_variable = Scanner(System.`in`)
var variable_name = scanner_variable.nextLine()
For example,
var str = scanner.nextLine()
Read Data Input using Scanner Example Program in Kotlin
// Read Data Input in Kotlin example program
// Data Input Kotlin Programs, Basic Kotlin Programs
import java.util.Scanner
fun main(args: Array<String>) {
val scanner = Scanner(System.`in`)
val num1 = scanner.nextInt()
println("The input one is : $num1")
val num2 = scanner.nextInt()
println("The input two is : $num2")
val sum = num1+num2
println("The sum of the two inputs is : $sum")
}
Sample Output
Enter the inputs for addition
10
The input one is : 10
100
The input two is : 100
The sum of the two inputs is : 110