I'm trying to do a question on my study guide that asks:
Write an exception-controlled loop that loops until the user enters an integer between 1 and 5.
I can't decipher what this question really means since I've never heard of that term before, but this is my best guess:
Scanner input = new Scanner(System.in);
int a = 0;
while(a <= 0 || a > 5)
{
try {
a = input.nextInt();
if(a <= 0 || a > 5)
throw new OutOfRangeException(); //my own Excpt. class
} catch (OutOfRangeException e) {
System.out.println(e.getMessage());
}
}
What do you you guys think? Am I missing something here?
I think that your catch clause should be outside the loop
Scanner input = new Scanner(System.in);
int a = 0;
try
{
while(true)
{
a = input.nextInt();
if(a <= 0 || a > 5)
throw new OutOfRangeException(); //my own Excpt. class
}
}
catch (OutOfRangeException e) {
System.out.println(e.getMessage());
}
I haven't actually heard the term "exception controlled loop", but I think it means that it's an infinite loop that exits upon exception. Seems logical.
As the comments say, if you need to loop until the user enters a number between 1 and 5, the condition to throw should be
if(a >= 1 && a <= 5)
"Exception-controlled" is not a standard term, and anyway, using exceptions for control flow is a well-known bad practice. But to demonstrate it most clearly (i.e. badly), I would leave out the loop check and just write while(true)
so that the loop is obviously only controlled by the exception.
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