Search code examples
javaif-statementjoptionpane

I am trying to set a requirement to only enter an integer and if anything else ins entered show error message


        ans = JOptionPane.showInputDialog(null,"There are currently "+clubSize+" people inside right now" +
                                                            "\nHow many People are in your party today.");
        int partyIn;
        try
            {
           partyIn = Integer.parseInt(ans);
            }
        catch (NumberFormatException e)
            {
           JOptionPane.showMessageDialog(null, "What you entered was not a number: " + ans);
            }
        if (clubSize + partyIn <= 125)
            {
            clubSize = clubSize + partyIn; 
            peopleIn = peopleIn + partyIn;
            }
        else
            {
            JOptionPane.showMessageDialog(null, "Sorry you have to many people in your party");
            }

this is coming back with a error: variable partyIn might not have been initialized


Solution

  • Use the fact that Integer.parseInt will throw a NumberFormatException if the inputted number isn't a real number. Catch that exception and then notify the user of the error.

    int partyIn;
    try
    {
       partyIn = Integer.parseInt(ans);
    }
    catch (NumberFormatException e)
    {
       JOptionPane.showMessageDialog(null, "What you entered was not a number: " + ans);
    }