如何将命令放在JOptionPane.showInputDialog上的按钮上

时间:2018-03-24 20:15:08

标签: java netbeans netbeans-8

所以我环顾四周并看到了一些类似的问题,但我仍然无法让我的计划工作。我只是在家练习(我在高中)不能解决这个问题并继续前进。这是我的代码,但我不确定我做错了什么。

    String inputAge, outputOK, outputCancel;
    Integer Age;

    inputAge = JOptionPane.showInputDialog("Enter Age To Find Your Year Of Birth", JOptionPane.OK_CANCEL_OPTION);


    if (inputAge == JOptionPane.OK_OPTION){

        System.out.println("You Were Born In The Year " + (2018 - (Age = Integer.parseInt(inputAge))));

    } else if (inputAge == JOptionPane.CANCEL_OPTION){
        System.exit(1);
    }

2 个答案:

答案 0 :(得分:1)

  

表示第一种类型:java.lang.String,第二种类型:int。

showInputDialog(...)方法返回String,而不是int。所以你不能只将值赋给int。您需要将String转换为int。类似的东西:

String value = JOptionPane.showInputDialog(...);
int age = Integer.parseInt(value);

答案 1 :(得分:0)

在您的代码中,您有两个错误:

如果您使用 IDE 而非 TextEditor 编写代码,则会检测到无法将inputAgeOK_OPTION进行比较,因为:

inputAge 字符串OK_OPTION静态整数

第二个错误是if (inputAge == JOptionPane.OK_OPTION),假设您将inputAge的结果转换为Integer,如下所示:Integer.valueOf(inputAge)我们得到结果:

if (Integer.ValueOf(inputAge) == JOptionPane.OK_OPTION)但是如果你在JOptionPane class中出亲,你会发现JOptionPane.OK_OPTIONpublic static final int OK_OPTION = 0;,这意味着这部分代码:

if (inputAge == JOptionPane.OK_OPTION){

        System.out.println("You Were Born In The Year " + (2018 - (Age = Integer.parseInt(inputAge))));

    } 

仅在用户写 0 时才执行,我不完全知道您的观点,但我认为逻辑是:

  

我们使用JOptionPane.showInputDialog(参数)来询问用户   在我们对此值进行测试之后键入一个String。

在您的代码中,您对最终的static 变量进行了测试,因此我猜您的代码将是这样的:

inputAge = JOptionPane.showInputDialog("Enter Age To Find Your Year Of Birth", JOptionPane.OK_CANCEL_OPTION);
    if (inputAge != null) {
        if (!inputAge.isEmpty()) {
            if (Integer.valueOf(inputAge) != 0) {

                System.out.println("You Were Born In The Year " + (2018 - (Age = Integer.parseInt(inputAge))));

            }
        }
    }

使用此方法,您的代码可以获取输入并计算结果。

相关问题