#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    1
    Rep Power
    0

    [Homework] Do-While Try-Catch exception repeating


    Hello everyone, thank you for opening my topic.

    I am working on a very simple Exceptions-testing class.

    The program asks for Numerator and Denominator and then divides them and returns the quotient.

    I am trying to catch 2 exceptions. One of them is InputMismatchException (for non-numbers) and one of them is ArithmeticException (for dividing by 0).

    I am using Do-While so that when it catches, it will keep asking you until you get it correct.
    My issue at hand is this: when it catches the InputMismatchException, it constantly repeats the error message and the "Enter Numerator:" to no avail.

    This is because I have the Do-While being stopped after the Try has tried to get a numerator and denominator and carries out the rest, but the InputMismatchException is caught before it all executes. My code will help you understand better:

    import java.util.Scanner;
    import java.util.InputMismatchException;

    public class Quotient {

    public static void main(String[] args) {

    int dividend, divisor;
    Scanner scan = new Scanner(System.in);
    int keepTrying = 1;
    final int STOP_TRYING = 2;
    final int KEEP_TRYING = 1;

    do
    {
    try
    {
    System.out.print ("Enter the numerator: ");
    dividend = scan.nextInt();
    System.out.print ("Enter the denominator: ");
    divisor = scan.nextInt();

    System.out.println ("The fraction " + dividend + "/" +
    divisor + " is equal to " + intQuotient(dividend, divisor) + ".");
    keepTrying = STOP_TRYING;
    }
    catch (ArithmeticException e)
    {
    System.out.println("You cannot divide by zero!");
    }
    catch (InputMismatchException e)
    {
    System.out.println("You cannot divide by non-numbers or a number higher than 2,147,483,647.");
    }
    }
    while(keepTrying==KEEP_TRYING);


    }

    // Converts a fraction to a decimal by dividing the numerator
    // by the denominator
    private static int intQuotient (int n, int d)
    {
    int q = n / d;

    return q;
    }

    }


    Thank you all for reading. I tried to post the Pastebin link but, being a new account, I cannot post URLs. I look forward to all your responses!!!
    -Bradyarch
  2. #2
  3. Contributing User
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Aug 2010
    Location
    Eastern Florida
    Posts
    3,724
    Rep Power
    348
    Please edit your post and wrap the code in code tags to make the code easier to read.

IMN logo majestic logo threadwatch logo seochat tools logo