-
try and catch statements
right now with the code below, I can enter in a negative quantity and the try statement will succeed. If I enter in letters for numbers, for example, the try statement won't succeed, and the catch statement will be displayed. I also want to make the try statement not to succeed and the catch statement to trigger if I enter in a negative quantity. any idea how to do this?
Code:
try{
// create Scanner to read keyboard
Scanner sc = new Scanner( System.in );
// get title
System.out.print("Enter title: ");
String t = sc.nextLine();
// get quantity
System.out.print("Enter quantity: ");
int q = sc.nextInt();
}
catch( InputMismatchException e ){
System.out.println( "Input error... try again!" );
}
-
Code:
int q = sc.nextInt();
if (q < 0) throw new InputMismatchException();
Can't say I like the style much, though.
-Gary-
-
Yes Gary, I don't like that way too. But it's easiest way, than validating and looping conditions again and again, isn't it?
-
Thank you for the help :)
-
You are welcome, and thanks for marking the thread solved. :)