Try Catch - Help

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • millarAJ
    New Member
    • Mar 2008
    • 1

    Try Catch - Help

    [CODE=Java]public static int getQtyInStock()
    {
    int qtyInStock=0;
    boolean ok;
    do
    {
    ok=true;
    try
    {
    p("\n\t Qty in Stock : ");qtyInStock=k ey.nextInt();ke y.nextLine();
    }
    catch (InputMismatchE xception ex)
    {
    p("NON NUMERIC DATA HAS BEEN DETECTED - PLEASE RE-ENTER USING NUMERIC DATA ONLY!");
    ok=false;
    }
    catch(NumberFor matException ex)
    {
    p("NON NUMERIC DATA HAS BEEN DETECTED - PLEASE RE-ENTER USING NUMERIC DATA ONLY!");
    ok=false;
    }
    }while(!ok);

    return qtyInStock;
    }

    [/CODE]

    can anyone tell me why I am getting an infinite loop-----one of those days!
    Last edited by BigDaddyLH; Mar 7 '08, 05:17 PM. Reason: added code tags
  • BigDaddyLH
    Recognized Expert Top Contributor
    • Dec 2007
    • 1216

    #2
    Please enclose your posted code in [code] tags (See How to Ask a Question).

    This makes it easier for our Experts to read and understand it. Failing to do so creates extra work for the moderators, thus wasting resources, otherwise available to answer the members' questions.

    Please use [code] tags in future.

    MODERATOR

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      Suppose you type 'foo' when the program expects an integer; none of the characters
      are read, and exception is thrown, you catch it and print a message and try to
      read an integer again. There isn't any available ('foo' is still in the input buffer)
      and there the game repeats over and over again.

      kind regards,

      Jos

      Comment

      • BigDaddyLH
        Recognized Expert Top Contributor
        • Dec 2007
        • 1216

        #4
        If input is not an int, key.nextInt() blows up. When it blows up it leaves the input stream the way it found it and your code is repeatedly calling this method. Hence, inifinite loop.

        Suggestion: In this simple situation, Scanner isn't helping. Read input one line at a time with a BufferedReader and parse the line read.

        Comment

        Working...