mercredi 21 septembre 2016

How to validate multiple boolean checks in java

The following code has 2 boolen checks "agecheck" and "agecheck2". The code below will either have 2 error message or a error message after the code works. Both of the boolen statements are interfering with each other. Right now if I enter 1 it passes the first 2 validation statements it states my age and gender but then it says "Error: There must be at least 1 guest". So I would like my code to end with just stating my age and gender. I want the first 3 screens but not the forth ones.

import javax.swing.JOptionPane;
public class l{ 
public static void main (String[] args) { 
int age= Integer.parseInt(JOptionPane.showInputDialog( "Enter Age:"));

  boolean ageCheck = age ==1;

  if (ageCheck) {
    String gender =  JOptionPane.showInputDialog( "Enter Gender (F/M)");
    boolean genderCheck = gender.equalsIgnoreCase("M")  || gender.equalsIgnoreCase("F");

     if (genderCheck) {

           JOptionPane.showMessageDialog(null,"OUTPUT:  Your age is " + age + " and Gender is " + gender);

     } else { 

        JOptionPane.showMessageDialog(null,"Error:  Gender must be F or M") ;  
     }

  } else {

     JOptionPane.showMessageDialog(null,"Error: There must be atleast 1 guest") ;  

  }
  boolean ageCheck2 = (age>=2) && (age<=9);


  if (ageCheck2) {
    String gender =  JOptionPane.showInputDialog( "Enter Gender (F/M)");
    boolean genderCheck2 = gender.equalsIgnoreCase("M")  || gender.equalsIgnoreCase("F");

     if (genderCheck2) {

           JOptionPane.showMessageDialog(null,"OUTPUT:  YOUR 2 Years old and either a boy or girl");

     } else { 

        JOptionPane.showMessageDialog(null,"Error: You did not enter male or female as gender") ;  
     }

  } else {

     JOptionPane.showMessageDialog(null,"Error: There must be atleast 1 guest") ;  

  }

}}

Aucun commentaire:

Enregistrer un commentaire