JOptionPane 输入到 int
我试图让 JOptionPane 获取输入并将其分配给 int 但我遇到了变量类型的一些问题。
我正在尝试这样的事情:
Int ans = (Integer) JOptionPane.showInputDialog(frame,
"Text",
JOptionPane.INFORMATION_MESSAGE,
null,
null,
"[sample text to help input]");
但我得到:
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot
be cast to java.lang.Integer
这听起来合乎逻辑,我想不出另一种方法来实现这一点。
I am trying to make a JOptionPane get an input and assign it to an int but I am getting some problems with the variable types.
I am trying something like this:
Int ans = (Integer) JOptionPane.showInputDialog(frame,
"Text",
JOptionPane.INFORMATION_MESSAGE,
null,
null,
"[sample text to help input]");
But I am getting:
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot
be cast to java.lang.Integer
Which sounds logical yet, I cannot think of another way to make this happen.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
只需使用:
您无法将
String
转换为int
,但可以使用Integer.parseInt(string)
进行转换。Simply use:
You cannot cast a
String
to anint
, but you can convert it usingInteger.parseInt(string)
.这是因为用户插入到
JOptionPane
中的输入是一个String
,并且它以String
的形式存储和返回。Java本身无法在字符串和数字之间进行转换,你必须使用特定的函数,只需使用:
This because the input that the user inserts into the
JOptionPane
is aString
and it is stored and returned as aString
.Java cannot convert between strings and number by itself, you have to use specific functions, just use:
请注意,如果传递的字符串不包含可解析的字符串,则 Integer.parseInt 会引发 NumberFormatException。
Please note that Integer.parseInt throws an NumberFormatException if the passed string doesn't contain a parsable string.
现在,您的
Int_firstnumber
包含String_fristNumber
的整数值。希望有帮助
Now your
Int_firstnumber
contains integer value ofString_fristNumber
.hope it helped