Computer Science Canada Primitive Data Exception Prevention |
Author: | randint [ Thu Jan 05, 2012 9:54 am ] | ||||
Post subject: | Primitive Data Exception Prevention | ||||
Once in a while, you come across some programs that need to use Integer.parseInt (String) and other methods that converts a String into an int, but all of these methods have the risk of throwing some form of Exception if the String is not parseable. try...catch blocks cannot be looped, so you have no solution to this? What about the programs that you are using? The ones that tell you that something is not a valid number and lets you try again? Well, here is a Java program I made to do this trick (You do need to use this class every time the problem occurs, and use a do...while loop so that only if the boolean named "validate" is set to true can your loop exit and move on). An implementation of this class can be as the follows:
Note that the method
can only be used if Java version is 1.5 or higher. |
Author: | DemonWasp [ Thu Jan 05, 2012 10:20 am ] | ||
Post subject: | RE:Primitive Data Exception Prevention | ||
Err, try-catch blocks can be looped just fine.
Where'd you get an idea like that? But yes, there are plenty of ways of validating input, and you've found another one that certainly works. |
Author: | randint [ Thu Jan 05, 2012 11:25 am ] |
Post subject: | Implementation |
Here is a thing, if you are getting dozens or hundreds of inputs every single time, you'd need a lot of booleans...yes, my way of using do loop validation is brutal, it abuses the programmer to use a do loop for every single input. |
Author: | DemonWasp [ Thu Jan 05, 2012 11:38 am ] | ||
Post subject: | RE:Primitive Data Exception Prevention | ||
No, you would need one boolean, wrapped in a method. Ideally, to prompt for multiple integers, you'd do something like:
...or whatever, it's up to you and your application. But you should only have to write the loop once, with one flag variable; anything more is lunacy. |