简体   繁体   English

在Kotlin中获取空指针异常

[英]Getting null pointer exception in kotlin

The sum of a = 2.3 and b = 1.9 and the result should be 4. a = 2.3和b = 1.9的总和应为4。

So what I tried is to round the number by converting to Int but I am getting null pointer exception. 所以我试图通过转换为Int来舍入数字,但是我得到了空指针异常。

fun main() {

    val a = readLine()!!.trim().toFloat()
    val b = readLine()!!.trim().toFloat()
    val result = addNumbers(a,b)
}
fun addNumbers(a:Float, b:Float):Int{ //I should not change this function
    return a.toInt()+b.toInt()
}

You are likely running in some context where there's no standard input (such as https://play.kotlinlang.org/ , just for an example), because that's when readLine() returns null : 您可能会在没有标准输入的情况下运行(例如,例如https://play.kotlinlang.org/ ),因为那是readLine()返回null

Return the line read or null if the input stream is redirected to a file and the end of file has been reached. 如果将输入流重定向到文件并且已到达文件末尾,则返回读取行或null。

please provide the readLine() function. 请提供readLine()函数。 You use it as "throw an NPE if it is null" by adding !! 通过添加!!,可以将其用作“如果NPE为空则抛出NPE”。 to the call. 通话。 Better would be 更好的是

fun main() {

    val a = readLine()?.trim().toFloat()?: 0
    val b = readLine()?.trim().toFloat()?: 0
    val result = addNumbers(a,b)
}
fun addNumbers(a:Float, b:Float):Int{ //I should not change this function
    return a?.toInt()?:0+b?.toInt()?:0
}

there you get a 0 to add, when readLine is null 当readLine为null时,您将添加0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM