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
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