dimanche 27 septembre 2015

I want my program to display an error message when the user inputs anything other than an integer and loop it back

I am doing a project for my CS class and have everything done except for when users input anything that isn't an integer when I ask for their height, it gives an error. I'm not sure how to catch the exception. Here is a snippet of my source code. I'm a beginner and I really appreciate the help.

    JOptionPane.showMessageDialog (null, "This program calculates tidal volume.", "Tidal Volume Calculator", JOptionPane.INFORMATION_MESSAGE);
    name = JOptionPane.showInputDialog("What is your name?");

    while (flag3 == true)
    {
        sex = JOptionPane.showInputDialog("What is your sex?");

        if(sex.equalsIgnoreCase("male") || sex.equalsIgnoreCase("m"))
        {
            while (flag2 == true) 
            {
                height = Integer.parseInt(JOptionPane.showInputDialog("What is your height? (48-84 inches or 114-213 centimeters) \nEnter whole numbers only."));

                if(height <= 84 && height >= 48)
                {
                    malePbwInch = 50 + 2.3 * (height - 60);
                    JOptionPane.showMessageDialog(null, name + "'s predicted body weight is: " + malePbwInch);
                    flag2 = false;
                    flag3 = false;
                }
                if(height <= 213 && height >= 114)
                {
                    malePbwCm = 50 + .91 * (height - 152.4);
                    JOptionPane.showMessageDialog(null, name + "'s predicted body weight is: " + malePbwCm);
                    flag2 = false;
                    flag3 = false;
                }
                if(height > 84 && height < 114 || height < 48 || height > 213)
                {
                    JOptionPane.showMessageDialog(null, "Invalid height. Please try again.");
                }
                else
                {
                    try
                    {
                        malePbwInch = Integer.parseInt(height);
                    }
                    catch(NumberFormatException e)
                    {
                        JOptionPane.showMessageDialog(null, "Invalid height. Please try again.");
                    }
                }

            }
        }

Aucun commentaire:

Enregistrer un commentaire