jj smith jj smith - 2 months ago 5
Java Question

How to immeditaly end program with J.option in Java if validation is not correct

The following code ask for your name and age. If you enter age -99 the code still ask you for your Gender. I would like the code to immediately flash the error message if you do not enter a age between 0 and 100. Without asking for your gender. The code is listed below.

import javax.swing.JOptionPane;

public class l{
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"));
String gender = JOptionPane.showInputDialog( "Enter Your Gender (F/M)");

boolean ageCheck = age >0 && age <=100;
boolean genderCheck = gender.equalsIgnoreCase("M") || gender.equalsIgnoreCase("F");
//check to see if the age is within range
if (ageCheck) {
//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") ;

}






}//end main

}//end class

Answer

Just move the code that asks for gender inside the if branch corresponding to an acceptable age:

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") ;  

  }
}

If the logic gets any more complicated, I would suggest refactoring to isolate the logic for obtaining age and gender into separate methods. (I'd do it even for this code, but that's beyond the scope of what you asked about.)