Results 1 to 5 of 5
  1. #1
    vendetta is offline Member
    Join Date
    Jan 2010
    Posts
    31
    Rep Power
    0

    Default 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!" );
            }

  2. #2
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    Java Code:
               int q = sc.nextInt();
               if (q < 0) throw new InputMismatchException();
    Can't say I like the style much, though.

    -Gary-

  3. #3
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default

    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?

  4. #4
    vendetta is offline Member
    Join Date
    Jan 2010
    Posts
    31
    Rep Power
    0

    Default

    Thank you for the help :)

  5. #5
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

Similar Threads

  1. try catch help
    By vividcooper in forum New To Java
    Replies: 8
    Last Post: 02-11-2010, 10:00 AM
  2. how to catch two exceptions in one catch()?
    By arnab321 in forum New To Java
    Replies: 1
    Last Post: 11-06-2008, 11:54 AM
  3. try catch...
    By MarkWilson in forum New To Java
    Replies: 8
    Last Post: 06-27-2008, 06:39 PM
  4. Try Catch
    By Renegade85 in forum New To Java
    Replies: 4
    Last Post: 12-03-2007, 05:10 PM
  5. Use try and catch
    By zoe in forum New To Java
    Replies: 2
    Last Post: 07-25-2007, 08:50 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •