8

我正在尝试让 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

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

提前致谢

4

6 回答 6

9

只需使用:

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

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

于 2010-06-25T19:42:57.133 回答
5

这是因为用户插入到的输入JOptionPane是 aString并且它被存储和返回为 a String

Java不能自行在字符串和数字之间进行转换,你必须使用特定的函数,只需使用:

int ans = Integer.parseInt(JOptionPane.showInputDialog(...))
于 2010-06-25T19:43:48.973 回答
1
import javax.swing.*;
public class JOptionSample { 
    public static void main(String[] args) {

       String name = JOptionPane.showInputDialog("Enter First integer");

      String name2 = JOptionPane.showInputDialog("Enter second integer");

       JOptionPane.showMessageDialog(null, "The first inputted is 89 and the second 
    integers inputted is 45" );

    int number =Integer.parseInt(JOptionPane.showInputDialog(null, "89+45 = "));

    JOptionPane.showMessageDialog(null, "Question Message", "Title",
   JOptionPane.QUESTION_MESSAGE);

    int option = JOptionPane.showConfirmDialog(null, "Do you want to continue? ");
    JOptionPane.showMessageDialog(null, "Your choice is "+option);

    JOptionPane.showMessageDialog(null, " The sum of the two integers is : 134 ");
}
}
于 2021-10-14T04:38:50.253 回答
0

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

于 2010-06-25T21:12:21.250 回答
0
// 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);
    }
}
于 2016-04-06T18:05:50.143 回答
0
String String_firstNumber = JOptionPane.showInputDialog("Input  Semisecond");
int Int_firstNumber = Integer.parseInt(firstNumber);

现在您Int_firstnumber包含的整数值String_fristNumber

希望它有所帮助

于 2017-01-01T14:12:50.470 回答