I am trying to loop a try block every time an exception is thrown.
An example might be when the program prompts for a double and the user enters a string, so, a NumberFormatException is thrown. So the program will request the user to re-enter.
Here's what I am doing currently. Is this the proper way to do so or is there better way?
// infinite loop
for (;;)
{
try
{
//do something
break; // if an exception is not thrown. it breaks the loop.
}
catch (Exception e)
{
//display the stack trace.
}
// restarts the for loop
}
Instead of throwing exceptions according to the input, keep your restrictions on the user input by getting use of the regular expressions. Java regular expressions will help you at this point.
import java.util.Scanner;
import java.util.regex.Pattern;
public class Sample
{
private final static Pattern DIGITS = Pattern.compile( "\\d*" );
public static void main ( String [] args )
{
Scanner scanner = new Scanner( System.in );
while ( true )
{
String input = scanner.nextLine();
if ( evalInput( input ) )
process( input );
else
System.out.println("Input constraints: it must be just numerical.");
}
}
public static void process ( String str )
{
// Whatever you wanna do with the accepted input.
}
public static boolean evalInput ( String str )
{
if ( str != null && DIGITS.matcher( str ).matches() )
return true;
return false;
}
}
I'd do it just like you did, perhaps adding a prompt to re-enter.
while(true) {
try {
String s = read.nextLine();
i = Integer.parseInt(s);
break;
} catch(NumberFormatException) {
System.out.println("Please try again.");
continue;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With