-1

The sum of a = 2.3 and b = 1.9 and the result should be 4.

So what I tried is to round the number by converting to Int but I am getting null pointer exception.

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()
}
Star
  • 735
  • 3
  • 13
  • 34

2 Answers2

1

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:

Return the line read or null if the input stream is redirected to a file and the end of file has been reached.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
0

please provide the readLine() function. You use it as "throw an NPE if it is null" by adding !! 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

Phash
  • 428
  • 2
  • 7