Results 1 to 3 of 3

Thread: [RESOLVED] Try / Catch question

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Feb 2008
    Posts
    97

    Resolved [RESOLVED] Try / Catch question

    In my program I have multiple readLines for the user to enter in numbers, how would I do a try / catch to catch if they enter something other than a number? Could I just use one throw statement for all of them? Any help appreciated, thanks.


    Code:
    System.out.println("Enter Inventory Number : ");
    inventoryNumber = Integer.parseInt(reader.readLine());

  2. #2
    Fanatic Member
    Join Date
    Jul 2007
    Posts
    530

    Re: Try / Catch question

    If I get what you want
    vb Code:
    1. try {
    2.             System.out.println("Enter Inventory Number : ");
    3. int inventoryNumber = Integer.parseInt(reader.readLine());
    4.  
    5.         }
    6.     catch (Exception ex){
    7.         System.out.println("Enter a Number");
    8.     }

  3. #3
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: Try / Catch question

    Since you're using Integer.parseInt I assume you're trying to read an integer number. killer7k's code works fine but why wait for the JVM to throw the exception, which is always a bad idea you can do it in one of 2 ways:
    Code:
    Scanner s = new Scanner(System.in);
    inventoryNumber = s.nextInt();
    Or
    Code:
    Scanner s = new Scanner(System.in);
    String userInput = s.nextLine();
    if (userInput.matches("\\d+")) {
        inventoryNumber = Integer.parseInt(userInput);
    } else {
        System.err.println("Please enter an integer number");
    }
    The first way is better, the second is only for using the nextLine method.

    Oh and BTW use the Scanner class to read user input, it's easier to use and much safer
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

Posting Permissions

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



Click Here to Expand Forum to Full Width