所以我环顾四周,看到了一些类似的问题,但是我仍然无法让我的程序工作。我只是在家练习(我正在高中(无法解决这个问题,然后继续前进。这是我的代码,但我不确定我在做什么错。
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);
}
第一种类型:java.lang.string和第二种类型:int。
showInputDialog(...)
方法返回一个字符串,而不是int。因此,您不能仅将值分配给int。您需要将字符串转换为int。类似:
String value = JOptionPane.showInputDialog(...);
int age = Integer.parseInt(value);
在您的代码中您有两个错误:
如果您使用 IDE 而不是 textededitor 检测到无法将inputAge
与OK_OPTION
进行比较,因为:
inputAge
是 String 和OK_OPTION
是静态整数
第二个错误是if (inputAge == JOptionPane.OK_OPTION)
,假设您将输入结果转换为这样的整数:Integer.valueOf(inputAge)
,我们得到的结果是:
if (Integer.ValueOf(inputAge) == JOptionPane.OK_OPTION)
,但是如果您在 JOptionPane class
中超过exlore,您会发现 JOptionPane.OK_OPTION
是: public 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(参数(要求用户 在此之后键入A字符串,我们对此值进行测试。
在您的代码中,您对最终静态变量进行了测试,因此我想您的代码将是这样的:
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))));
}
}
}
使用此方法,您的代码可以获取输入并计算结果。