在我的程序中,我使用JOptionPane.showConfirmDialog来提示用户是否确定要退出模拟;如果你点击"否" prgoram应打印出来"继续siumlation ..."并继续使用该程序,但我发现当你点击否它打印出来"继续模拟"然后直接在"维护将不会执行,退出模拟......" 无论如何可以帮助我找出为什么会发生这种情况?
if(main.equalsIgnoreCase("N") | main.equalsIgnoreCase("NO")){
result = JOptionPane.showConfirmDialog(null, "WARNING! Are you sure you don't want to carry out maintenance? The simulation will stop if you click YES. ", "TERMINATE THE SIMULATION? ", JOptionPane.YES_NO_OPTION);
if(JOptionPane.NO_OPTION == result){
System.out.println("Continuing Simulation...");
}
if (JOptionPane.YES_OPTION == result) {
Result2 = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit the simulation?", "Are You Sure?", JOptionPane.YES_NO_OPTION);
}
if(JOptionPane.YES_OPTION == Result2){
System.out.println("Maintenance will not be carried out, exiting Simulation...");
try{
System.exit(0);
}
finally{
System.err.println("Exiting...");
System.exit(1);
}
}
if (JOptionPane.NO_OPTION == Result2) {
System.out.println("Continuing simulation...");
}
}
答案 0 :(得分:3)
如果您点击"否"在第一个对话框中,您没有为Result2
分配任何值,因为您没有显示第二个对话框。但是,您仍然在此if语句Result2
中使用if(JOptionPane.YES_OPTION == Result2){
的值。
问题是,如果Result2
是一个实例变量,而您尚未为其分配值,则它具有类型int
的默认值,即零
常数JOptionPane.YES_OPTION
的值也为零。因此,if语句的计算结果为true
,并打印出维护消息并退出。
您应该嵌套if语句,以便只有在为其分配了有意义的值时才会检查Result2
的值,如下所示:
if (JOptionPane.YES_OPTION == result) {
Result2 = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit the simulation?", "Are You Sure?", JOptionPane.YES_NO_OPTION);
if(JOptionPane.YES_OPTION == Result2){
System.out.println("Maintenance will not be carried out, exiting Simulation...");
try{
System.exit(0);
}
finally{
System.err.println("Exiting...");
System.exit(1);
}
}
if (JOptionPane.NO_OPTION == Result2) {
System.out.println("Continuing simulation...");
}
}
答案 1 :(得分:0)
试试这个:
if(main.equalsIgnoreCase("N") | main.equalsIgnoreCase("NO")){
result = JOptionPane.showConfirmDialog(null, "WARNING! Are you sure you don't want to carry out maintenance? The simulation will stop if you click YES. ", "TERMINATE THE SIMULATION? ", JOptionPane.YES_NO_OPTION);
if(JOptionPane.NO_OPTION == result){
System.out.println("Continuing Simulation...");
}else{
if (JOptionPane.YES_OPTION == result) {
Result2 = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit the simulation?", "Are You Sure?", JOptionPane.YES_NO_OPTION);
}
if(JOptionPane.YES_OPTION == Result2){
System.out.println("Maintenance will not be carried out, exiting Simulation...");
try{
System.exit(0);
}
finally{
System.err.println("Exiting...");
System.exit(1);
}
}
if (JOptionPane.NO_OPTION == Result2) {
System.out.println("Continuing simulation...");
}
}}
您需要在if(JOptionPane.NO_OPTION == result)
答案 2 :(得分:0)
if(main.equalsIgnoreCase(“N”)| main.equalsIgnoreCase(“NO”))使用按位包含OR运算符“|”。尝试使用逻辑OR运算符“||”代替:
if(main.equalsIgnoreCase("N") || main.equalsIgnoreCase("NO")){