我在使用一个非常基础的初级 Java 程序时遇到了一些问题。我有一个函数,它应该根据用户对 JOptionPane YES_NO_OPTION 消息框的响应返回一个值。该程序运行良好,直到您看到重新开始或退出的选项。无论你选择哪个选项,是或否,它都会带你回去做一个新的循环。我知道解决此问题的一种方法就是依靠取消按钮,但我想了解为什么此代码未返回我期望的值,因此非常感谢您的帮助。
import javax.swing.JOptionPane;
public class HelloMK2 {
public static void main(String[] args) {
for (int i = 0; i < 3000; i++) {
double Int1 = optiontakeshape();
double Int2 = optiontakediam();
if (Int1 == 1.0) {
Shape s1 = new Circle(Int2);
infoBox(s1.area2d());
} else {
Shape s1 = new Sphere(Int2);
infoBox(s1.volume());
}
int yesno = repeat();
if (yesno == 1) {
System.out.println(yesno);
break;
}
}
}
public static int repeat() {
int j;
int g = JOptionPane.YES_NO_OPTION;
JOptionPane.showConfirmDialog(null, "Would you like to begin again?",
"Repeat?", g);
if (g == JOptionPane.NO_OPTION) {
j = 1;
System.exit(0);
} else if (g == JOptionPane.YES_OPTION) {
j = 2;
} else {
j = 3;
System.exit(0);
}
System.out.println(j);
return j;
}
//...
}
编辑:感谢您的快速回复。我实际上并没有测试是/否结果的值(value)。我现在实现的代码是:
public static int repeat ()
{
int j;
if (JOptionPane.showConfirmDialog(null, "Would you like to begin again?", "Repeat?", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION){
j = 2;
} else {
j = 1;
//System.exit(0); escaped so I could test the break point was working properly
}
System.out.println(j);
return j;
}
最佳答案
这是你的问题。
int g = JOptionPane.YES_NO_OPTION;
g
将始终是 YES_NO_OPTION
,在整数值方面与 YES_OPTION
相同。两者均为 0。
试试这个
int g = JOptionPane.showConfirmDialog(null, "Would you like to begin again?", "Repeat?", JOptionPane.YES_NO_OPTION);
关于java - JOptionPane YES_NO_OPTION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20924149/