NumberFormatException in Kotlin

58 Views Asked by At

I was solving a question on CodeChef. A specific line to take input like:

10 232 4543

I was willing to store it in variables and then perform the calculation.

The following is the line of code I am using to achieve this.

val (d,l,r) = readLine()!!.split(" ").map{ it -> it.toInt()}

This line worked for previous question but is not working for the current question. I am inserting my code and the link to the question.


fun main(){
    var t = readLine()!!.toInt()
    for(i in 0 until t){
    val (d,l,r) = readLine()!!.split(" ").map{ it -> it.toInt()}
    if(d<l){
        println("Too Early")
    }
    else if(d>r){
        println("Too Late")
    }
    else{
        println("Take second dose now")
    }
    }
}

This is the link to the question: https://www.codechef.com/LP1TO201/problems/VDATES

The following is the error I am receiving.

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
    at java.base/java.lang.Integer.parseInt(Integer.java:678)
    at java.base/java.lang.Integer.parseInt(Integer.java:786)
    at ProgKt.main(prog.kt:4)
    at ProgKt.main(prog.kt)
1

There are 1 best solutions below

0
Marvin On

An empty string is not a number. There are two easy ways to solve this:

Filter empty strings using isEmpty():

val (d,l,r) = readLine()!!.split(" ").filterNot { it.isEmpty() }.map { it -> it.toInt() }

Use toIntOrNull() and only take non-null elements:

val (d,l,r) = readLine()!!.split(" ").mapNotNull { it -> it.toIntOrNull() }