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 

这听起来很合乎逻辑,我想不出另一种方法来实现这一点。

提前致谢

只需使用:

 int ans = Integer.parseInt( JOptionPane.showInputDialog(frame, "Text", JOptionPane.INFORMATION_MESSAGE, null, null, "[sample text to help input]")); 

您不能将String转换为int ,但可以使用Integer.parseInt(string)转换它。

这是因为用户插入JOptionPane的输入是一个String ,它存储并作为String返回。

Java无法在字符串和数字之间进行转换,您必须使用特定的函数,只需使用:

 int ans = Integer.parseInt(JOptionPane.showInputDialog(...)) 

请注意,如果传递的字符串不包含可解析的字符串,则Integer.parseInt会抛出NumberFormatException。

 // sample code for addition using JOptionPane import javax.swing.JOptionPane; public class Addition { public static void main(String[] args) { String firstNumber = JOptionPane.showInputDialog("Input "); String secondNumber = JOptionPane.showInputDialog("Input "); 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); } } 
 String String_firstNumber = JOptionPane.showInputDialog("Input Semisecond"); int Int_firstNumber = Integer.parseInt(firstNumber); 

现在你的Int_firstnumber包含Int_firstnumber整数值。

希望它有所帮助