简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM