Hello forum! My name is Will and I'm super new to Java. I'm trying to create a program that won't let a user enter in a letter or double value in a do-while loop that is focused on gathering integer data. I want to make it so if an error occurs, there will be a catch, clear, and then have the user retry entering in data. How do I setup a try-catch statement that will stop errors, clear them, and have the user enter in new data?
Bear Bibeault wrote:What kind of errors are you talking about? If you mean data entry errors then those are not the type that you'd handle with exceptions, but with normal program control flow.
Basically, integer input errors. Let's say the method asks for an integer such as, "Type in a number: " and the user accidentally hits, "5t." An error would then throw and then clear the data to have the user try again.
Campbell Ritchie wrote:Welcome to the Ranch! Have you studied the methods of the well‑known Scanner class? If you use them correctly you can avoid using Exceptions at all.
I have not actually. Thanks for that info! I'll see what I can use.
Will Pritchard wrote:Basically, integer input errors. Let's say the method asks for an integer such as, "Type in a number: " and the user accidentally hits, "5t." An error would then throw and then clear the data to have the user try again...
In addition to Campbell's suggestion, you might want to have a look at the UserInput page. Getting input from a user is not easy - as I suspect you're finding out - and there are a lot of things that can go wrong.
I should add that it shows you one way to do it, and there are are many others; but hopefully it gives you something to think about.
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop