Results 1 to 5 of 5
Thread: try and catch statements
- 05-23-2010, 08:02 AM #1
Member
- Join Date
- Jan 2010
- Posts
- 31
- Rep Power
- 0
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?
Java 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!" ); }
- 05-23-2010, 08:58 AM #2
Senior Member
- Join Date
- Mar 2010
- Posts
- 953
- Rep Power
- 4
Can't say I like the style much, though.Java Code:int q = sc.nextInt(); if (q < 0) throw new InputMismatchException();
-Gary-
- 05-23-2010, 02:32 PM #3
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
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?
- 05-23-2010, 05:42 PM #4
Member
- Join Date
- Jan 2010
- Posts
- 31
- Rep Power
- 0
Thank you for the help :)
- 05-23-2010, 05:46 PM #5
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
You are welcome, and thanks for marking the thread solved. :)
Similar Threads
-
try catch help
By vividcooper in forum New To JavaReplies: 8Last Post: 02-11-2010, 09:00 AM -
how to catch two exceptions in one catch()?
By arnab321 in forum New To JavaReplies: 1Last Post: 11-06-2008, 10:54 AM -
try catch...
By MarkWilson in forum New To JavaReplies: 8Last Post: 06-27-2008, 05:39 PM -
Try Catch
By Renegade85 in forum New To JavaReplies: 4Last Post: 12-03-2007, 04:10 PM -
Use try and catch
By zoe in forum New To JavaReplies: 2Last Post: 07-25-2007, 07:50 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks