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