如果验证不正确,如何在 Java 中使用 J.option 立即结束程序
How to immeditaly end program with J.option in Java if validation is not correct
ane.showMessageDialog(空,"Error: Gender must be F or M");
}
} else {
//Write an error for invalid Age
JOptionPane.showMessageDialog(null,"Erlll") ;
}
}//end main
}//end class
只需将要求性别的代码移动到 if
对应可接受年龄的分支中:
public static void main (String[] args) {
final int DRINKING_AGE = 21;
final int ADULT = 18;
final String LEGAL_DRINKING_AGE_MESSAGE = "You are legally able to drink";
int age = Integer.parseInt(JOptionPane.showInputDialog( "Enter Your Age"));
boolean ageCheck = age >0 && age <=100;
//check to see if the age is within range
if (ageCheck) {
String gender = JOptionPane.showInputDialog( "Enter Your Gender (F/M)");
boolean genderCheck = gender.equalsIgnoreCase("M") || gender.equalsIgnoreCase("F");
//check to see if the user entered M or F
if (genderCheck) {
//if we pass both checks, then do the rest of the logic
JOptionPane.showMessageDialog(null,"OUTPUT: Your age is " + age + " and Gender is " + gender);
} else {
//Write an error for invalid Gender
JOptionPane.showMessageDialog(null,"Error: Gender must be F or M") ;
}
} else {
//Write an error for invalid Age
JOptionPane.showMessageDialog(null,"Error: Age must be between 0 -100") ;
}
}
如果逻辑变得更复杂,我建议重构以将获取年龄和性别的逻辑分离到单独的方法中。 (即使是这段代码我也会这样做,但这超出了你所询问的范围。)
ane.showMessageDialog(空,"Error: Gender must be F or M");
}
} else {
//Write an error for invalid Age
JOptionPane.showMessageDialog(null,"Erlll") ;
}
}//end main
}//end class
只需将要求性别的代码移动到 if
对应可接受年龄的分支中:
public static void main (String[] args) {
final int DRINKING_AGE = 21;
final int ADULT = 18;
final String LEGAL_DRINKING_AGE_MESSAGE = "You are legally able to drink";
int age = Integer.parseInt(JOptionPane.showInputDialog( "Enter Your Age"));
boolean ageCheck = age >0 && age <=100;
//check to see if the age is within range
if (ageCheck) {
String gender = JOptionPane.showInputDialog( "Enter Your Gender (F/M)");
boolean genderCheck = gender.equalsIgnoreCase("M") || gender.equalsIgnoreCase("F");
//check to see if the user entered M or F
if (genderCheck) {
//if we pass both checks, then do the rest of the logic
JOptionPane.showMessageDialog(null,"OUTPUT: Your age is " + age + " and Gender is " + gender);
} else {
//Write an error for invalid Gender
JOptionPane.showMessageDialog(null,"Error: Gender must be F or M") ;
}
} else {
//Write an error for invalid Age
JOptionPane.showMessageDialog(null,"Error: Age must be between 0 -100") ;
}
}
如果逻辑变得更复杂,我建议重构以将获取年龄和性别的逻辑分离到单独的方法中。 (即使是这段代码我也会这样做,但这超出了你所询问的范围。)