Standard input in Kotlin
Standard input
Standard input is a stream of data that goes into the program. By default, standard input gets data from the keyboard but it is possible to get it from a file.
- Kotlin functions
- Kotlin has a useful function to read data from the standard input. It is supported by the operating system. It is readline. It reads the whole line as a string.
fun main() {
val line = readLine()!!
println(line)
}
- If you need to get a number from the input, you can use this construction:
fun main() {
val line = readLine()?.toInt()!!
println(line)
}
- To accept multiple words in a single use the following code
val (a, b) = readLine()!!.split(' ')
println("$a, $b")
val (c, d, e) = readLine()!!.split(' ')
println("$c, $d, $e")
- To accept multiple words in a single use the following code
val (a, b) = readLine()!!.split(' ')
println("$a, $b")
val (c, d, e) = readLine()!!.split(' ')
println("$c, $d, $e")
- Java Scanner
- Another way to obtain data from the standard input is to use the Java Scanner.
- Scanner allows a program to read values of different types (strings, numbers, etc) from the standard input.
- You can use any method to add Scanner to your program.
val scanner = Scanner(System.`in`)
- Scanner.next() reads only one word, not a line. If the user enters Hello, Kotlin, it will read Hello,
- It's possible to read a number as a string using scanner.next() or scanner.nextLine() methods, if the number is on a new line.
fun main() {
val scanner = Scanner(System.`in`)
val line = scanner.nextLine()
val number = scanner.nextInt()
val string = scanner.next()
println(line)
println(number)
println(string)
}
- Also, the Scanner type provides several methods (functions) for reading values of other types. Read Class Scanner.
Invoking functions
- A function is a sequence of instructions, we can invoke it from a program by calling its name.
- Functions arguments
- When we want to use a function, we can invoke (or call) it using its name followed by parentheses.
- If a function takes one or more arguments (input data), they should be passed in the parentheses.
- Producing a result
- Some functions not only take arguments but also produce (return) some results.
- All functions return a result, even the println function. The result is a special value called Unit that practically means no result.
Do's and Don'ts
- Scanner.next() reads only one word, not a line. If the user enters Hello, Kotlin, it will read Hello,
Comments
Post a Comment