0

I am currently working on a program which accepts a user input through the JOptionPane window. My goal is to create an if statement which validates the user input as an integer. I've tried the Integer.parseInt method but that just throws an exception, so I cannot display my own JOptionPane window informing the user of the mistake. I'm very new to programming and cannot think of another way to convert the string to an integer (or at least another way that works) for use in the if statement. Ideas?

Thanks!

2
  • 2
    Post the code you have tried. It's hard for us to help you when we don't know what you did. Commented Mar 8, 2012 at 5:11
  • The easiest thing would be to catch the exception and handle it. Commented Mar 8, 2012 at 5:14

1 Answer 1

2

If you are to get an integer somehow after the JOptionPane message is displayed, you may want to take a look at this code which continuously prompts the user to enter a valid integer:

int number = 0;
boolean ok = false;
String input = "";

while(!ok)
{
    try
    {
        number = Integer.parseInt( input );
        ok = true;
    }
    catch(Exception e)
    {
        // Change your JOptionPane message here to warn the user.
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.