I am writing a program for school where the user inputs their age into a String which is then converted to an integer. When a value that cannot be converted to an int is input, an exception is thrown. I have written the code for this, but I am not sure how to loop the try-catch statement to terminate only when an int value is input.

I am planning on using a while loop that will terminate when a correct value is input, yet I am unsure as to what variable I can test for my loop to terminate...
This is an example:

while (<an exception is thrown>);
         try
        {
            int age = Integer.parseInt(ageyrs);
            System.out.println("Your age is "+age);
        }
        catch(NumberFormatException n)
        {
            System.out.println("Incorrect data format");
            System.out.println(n);
        }

Can someone please offer advice if you have any.
If my problem is unclear, do let me know.
Thanks

The while takes as "argument" a boolean expression. So why don't you use a boolean.
At first have it to be true, so you will enter the loop. If the user enters correct String that can be converted into a number, meaning that this: Integer.parseInt will execute, make that variable false. That will make the loop exit

Thanks for the suggestion. much appreciated :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.