Kotlin(Intellij)中的NumberFormateXception

发布于 2025-02-10 20:29:31 字数 616 浏览 2 评论 0原文

这是我想做的,我希望用户输入任何数字,并且应该显示它,但是我会遇到此错误。 导入java.util。*

这是我的代码

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

,我遇到的错误是

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

執念 2025-02-17 20:29:31

您正在在40的前面编写一个空间,如错误“ 40”所示。

解决方案可能是将所有领先和尾随的空间从阅读线中进行修剪,例如:

var age = readLine()!!.trim().toInt()

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文