为什么我不能使用这个源代码在Kotlin中添加两个数字?

时间:2016-12-22 18:21:01

标签: kotlin

这是我创建的用于添加两个数字的代码:

import java.util.*

fun main(args: Array<String>) {
    val (a, u) = readLine()!!.split(' ').map(String::toInt)

    println(add(a, u))
}

fun  add(a: Int, u: Int) = a + u

但是我一直收到这个错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:592)
    at java.lang.Integer.parseInt(Integer.java:615)
    at Kotlin_learnKt.main(kotlin^learn.kt:6)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

Process finished with exit code 1

我不确定我做错了什么。我只想提示用户输入两个数字,让代码添加它们,然后返回结果。

2 个答案:

答案 0 :(得分:2)

从抛出的异常堆栈跟踪中,它看起来不像是在输入任何内容,因此readLine()返回无法解析为int值的空字符串。

我建议您在排除故障时单独读取每个int值:

fun readInt(message: Any?): Int {
    print(message)
    return readLine()!!.toInt()
}
val a = readInt("a = ")
val u = readInt("u = ")
println("a + u = ${a + u}")

或者如果你想得到幻想:

fun readInt(message: Any?): Int {
    val promptSequence = generateSequence(
            seedFunction = {
                print(message)
                readLine()
            },
            nextFunction = { invalidInput ->
                println("Input '$invalidInput' is not an int value. Try again.")
                print(message)
                readLine()
            }
    )

    return promptSequence.map(::Scanner).first(Scanner::hasNextInt).nextInt()
}

val a = readInt("a = ")
val u = readInt("u = ")
println("a + u = ${a + u}")

答案 1 :(得分:0)

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)
}