Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NumberFormatException in Kotlin (IntelliJ)

Here is what I am trying to do, I want the user to enter whatever number and it should be displayed, but I am getting this error.
import java.util.*

This is my code

fun main(){
print("Enter your age")
var age = readLine()!!.toInt()
print(age)
}

And the error I am getting is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Enter your age 40
Exception in thread "main" java.lang.NumberFormatException: For input string: " 40"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:654)
at java.base/java.lang.Integer.parseInt(Integer.java:784)
at HelloKt.main(Hello.kt:5)
at HelloKt.main(Hello.kt)

Process finished with exit code 1

>Solution :

You are writing a space in front of the 40 as indicated by the error " 40".

A solution could be is to trim all leading and trailing whitespaces from the readLine, like this:

var age = readLine()!!.trim().toInt()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading