I'm having a little trouble with one of my exceptions. The following code is just a simple division of two integers. I have built two exception to handle an InputMismatch and divide by zero. What I want to happen is when there is an exception, I want the program to return to let the user enter more data. If there is no exception, I want the program to end. The problem occurs when I enter words instead of numbers to make the exception InputMismatch work. When this happens the program goes into an infinity loop and I have to kill the program. Can somebody please look at my code and let me know what I'm doing wrong?

Also, do I need a throw for the InputMismatch?

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

public class P4Exceptions
{
    public static void main(String[] args)
    {

	 Scanner scan = new Scanner(System.in);
	 int n1, n2;
	 double r = 0;
	 boolean continueLoop = true; // determines if more input is needed
	 
  	  while ( continueLoop )
  	  {
            try
            {
                System.out.println("Enter two numbers. I will compute the ratio:");
 	        n1 = scan.nextInt();
	        n2 = scan.nextInt();
	        r = (double) n1 / n2; 
	        
                if (n2 == 0)
                    throw new ArithmeticException();	          
     
                System.out.println("The ratio r = " + r );
                continueLoop = false;
 
        }

        catch ( ArithmeticException arithmeticException )                
        {                                                                
            System.out.println("There was an exception: Divide by zero. Try again\n");
        }    
        catch ( InputMismatchException inputMismatchException )          
        {                                                                
           System.out.println("You must enter an integer. Try again.\n");    
        } 
         	
	   }                         	 

}
}

I think it has something to do with the way the stream works--

if you call the method nextInt it will return the value on the line and attempt to the next line of code.

I'm almost certain that because the type returned was not the type that should be returned, the method nextInt threw an exception and most likely returned 0 (since the method is an int and must therefore return a valid argument). Upon doing so, the stream might not have been flushed, leaving the value on the line and for it to be re-evaluated again since the line jump was unsuccessful.

Here is the edit--

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

public class P4Exceptions
{
	public static void main(String[] args)
	{

	Scanner scan = new Scanner(System.in);
	int n1, n2;
	double r = 0;
	boolean continueLoop = true; // determines if more input is needed

		while ( continueLoop )
		{
			try
			{
				System.out.println("Enter two numbers. I will compute the ratio:");
				n1 = Integer.parseInt(scan.nextLine());
				n2 = Integer.parseInt(scan.nextLine());
				r = (double) n1 / n2;

				if (n2 == 0)
				throw new ArithmeticException();

				System.out.println("The ratio r = " + r );
				continueLoop = false;

			}
			catch ( ArithmeticException arithmeticException )
			{
				System.out.println("There was an exception: Divide by zero. Try again\n");
				n1 = 0;
				n2 = 0;
			}
			catch ( NumberFormatException inputMismatchException )
			{
				System.out.println("You must enter an integer. Try again.\n");
				n1 = 0;
				n2 = 0;
			}
			catch(Exception e)
			{
				System.out.println(e);
                                n1 = 0;
                                n2 = 0;
			}

		}

	}
}
commented: Excellent post!! Thanks for the help!! +1

I think I might have made the same mistake. The way Scanner works, is by matching patterns in some stream. When you use nextInt() it will attempt to find an integer value in the input stream. If it is successful, it will move forward in the stream. If it is not successful then it will not move forward. Thus when you input words, you remain on the same input until you call the appropriate Scanner method to match it and proceed.

So add scan.nextLine(); after the line with your message: System.out.println("You must enter an integer. Try again.\n"); So you'd have:

catch (InputMismatchException inputMismatchException)
{                                                                
    System.out.println("You must enter an integer. Try again.\n");    
    scan.nextLine();
}

This will allow the scanner object to skip the error and move forward in the input stream. By the way, perhaps if would be best to check if n2 is zero before actually doing the division :icon_wink: it works regardless, but it's still an unneeded calculation if there is an error.

commented: Excellent post!!! Thanks for the help +1

Thank you both for your answers!! They were both really helpful!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.