Reading console input in Kotlin

2019-02-02 23:22发布

问题:

I am attempting to accept input from the console in Kotlin but it is difficult because I am not too sure about the syntax.

I begin with the main

fun main(args: Array<String>) {

}

WHAT should I enter after this? I am aware that the println() and readline() are involved but I do not know how to structure them.

Objective: prompt user to enter a number, the number entered is multiplied by 6, program returns the result to the console display.

回答1:

Here are A+B examples in Kotlin reading from stdin:

fun main(vararg args: String) {
  val (a, b) = readLine()!!.split(' ')
  println(a.toInt() + b.toInt())
}

or

fun main(vararg args: String) {
  val (a, b) = readLine()!!.split(' ').map(String::toInt)
  println(a + b)
}

or

fun readInts(separator: Char = ' ') = readLine()!!.split(separator).map(String::toInt)

fun main(vararg args: String) {
  val (a, b) = readInts()
  println(a + b)
}

or

import java.util.Scanner

fun main(vararg args: String) {
  val input = Scanner(System.`in`)
  val a = input.nextInt()
  val b = input.nextInt()
  println(a + b)
}

or

with(Scanner(System.`in`)) {
    val a = nextInt()
    val b = nextInt()
    println(a + b)
}

Beware that Scanner is somewhat slow. This may be important in some cases like competitive programming where program's execution on large inputs could be made up to two times faster just by replacing Scanner with plain readLine.

I hope someday a concise, crossplatform, performant, universal for both console and files input parsing support would be introduced in Kotlin stdlib. Like readInt, readLong, etc global and Reader extension functions.


Bonus

Sometimes you start with console input/output but then need to switch to files. It becomes too tedious to prepend every read or write call with file stream variable.

Here is a peace of Kotlin magic that allows to just wrap unchanged console code with a couple of lines to force it read and write to files also ensuring they are closed properly:

fun <T : Closeable, R> T.useWith(block: T.() -> R): R = use { with(it, block) }

File("a.in").bufferedReader().useWith {
    File("a.out").printWriter().useWith {
        val (a, b) = readLine()!!.split(' ').map(String::toInt)
        println(a + b)
    }
}

Scanner(File("b.in")).useWith {
    PrintWriter("b.out").useWith {
        val a = nextInt()
        val b = nextInt()
        println(a + b)
    }
}

Wrapping lines can be quickly commented out when happens a need to switch back to console.



回答2:

Use readLine() to take input from user, ATQ:

    fun main(args:Array<String>){
    print("Enter a number")
    var variableName:Int = readLine()!!.toInt()  // readLine() is used to accept the String value and ".toInt()" will convert the string to  Int. 
    var result:Int= variableName*6
    print("The output is:$result") 
    }


回答3:

fun readInts(separator: Char = ' ') = 
readLine()!!.split(separator).map(String::toInt)
fun main(args: Array<String>) {
    var A : List<Int> = readInts()
}


回答4:

By default readLine takes input as string toInt can be used to convert it to integer

fun main(args:Array<String>){
    var first: Int
    var second: Int
    println("Enter the first number")
    first = readLine()!!.toInt()
    println("Enter the second number")
    second= readLine()!!.toInt()
    println("The sum is ${first + second}")
}