0
        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

1 Answers1

1

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);
}
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • I have never used the try or catch code before so excuse me if this is a dumb question, but I edited my code above and put it the way you had it but it is coming up with an error. – JonMichael Feb 28 '13 at 20:32
  • What we've done here is created a possibility of the `partyIn` variable not being initialized. Assuming that your code is in a method, try a `return` statement inside the `catch` block, so that if the code gets past the catch block, then the compiler knows that `parseInt` succeeded, and that `partyIn` has been initialized. – rgettman Feb 28 '13 at 20:36
  • adding in the return statement allows it to compile and sends the error message, but it just ends the program, do i just add in a loop to get it to ask the question again? – JonMichael Feb 28 '13 at 20:46
  • Actually to get it to work I added in a while(true) loop and added a break in the catch instead of a return and this seemed to work. Thank you for your help though. – JonMichael Feb 28 '13 at 20:57