Java JOptionPane 输入到 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3120922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JOptionPane Input to int
提问by kxk
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.
我试图让 JOptionPane 获得一个输入并将它分配给一个 int 但我在变量类型方面遇到了一些问题。
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.
这听起来合乎逻辑,但我想不出另一种方法来实现这一目标。
Thanks in advance
提前致谢
采纳答案by jjnguy
Simply use:
只需使用:
int ans = Integer.parseInt( JOptionPane.showInputDialog(frame,
"Text",
JOptionPane.INFORMATION_MESSAGE,
null,
null,
"[sample text to help input]"));
You cannot cast a String
to an int
, but you can convert it using Integer.parseInt(string)
.
您不能将 a转换String
为 an int
,但可以使用Integer.parseInt(string)
.
回答by Hyman
This because the input that the user inserts into the JOptionPane
is a String
and it is stored and returned as a String
.
这是因为用户插入的输入JOptionPane
是 aString
并且它被存储并作为 a 返回String
。
Java cannot convert between strings and number by itself, you have to use specific functions, just use:
Java本身无法在字符串和数字之间进行转换,您必须使用特定的函数,只需使用:
int ans = Integer.parseInt(JOptionPane.showInputDialog(...))
回答by Davy Meers
Please note that Integer.parseInt throws an NumberFormatException if the passed string doesn't contain a parsable string.
请注意,如果传递的字符串不包含可解析的字符串,则 Integer.parseInt 会抛出 NumberFormatException。
回答by MyStack
// sample code for addition using JOptionPane
import javax.swing.JOptionPane;
public class Addition {
public static void main(String[] args) {
String firstNumber = JOptionPane.showInputDialog("Input <First Integer>");
String secondNumber = JOptionPane.showInputDialog("Input <Second Integer>");
int num1 = Integer.parseInt(firstNumber);
int num2 = Integer.parseInt(secondNumber);
int sum = num1 + num2;
JOptionPane.showMessageDialog(null, "Sum is" + sum, "Sum of two Integers", JOptionPane.PLAIN_MESSAGE);
}
}
回答by mubarak baloch
String String_firstNumber = JOptionPane.showInputDialog("Input Semisecond");
int Int_firstNumber = Integer.parseInt(firstNumber);
Now your Int_firstnumber
contains integer value of String_fristNumber
.
现在您Int_firstnumber
包含 的整数值String_fristNumber
。
hope it helped
希望它有帮助