I have implemented a catch statement for both the InputMismatchException and the ArithmeticException, how come they are not working?
Also, if the user enters "quit" for the numerator, the program should be able to exit. But my understanding is that as soon as the user enters something that is not an integer, the program goes to catch the exception. So, how can the "quit" option be included here?
The below is my program. Thanks!
import java.util.InputMismatchException;
import java.util.Scanner;
/**
*
*/
/**
* @author cathy
*
*/
public class IntegerDivision {
/**
* @param args
*/
static double result;
public static double division (int numerator, int divisor) {
result = numerator/divisor;
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int numerator=0, divisor=0;
Scanner sc = new Scanner (System.in);
boolean checkException = false;
do {
System.out.println("Enter the numerator (or 'quit'): ");
try {
numerator = sc.nextInt();
checkException = true;
}
catch (InputMismatchException e)
{
//if the user enters 'quit' then quit program, if else then do the following
System.out.println("Invalid data. Please enter an integer.");
sc.next();
}
} while (checkException == false);
checkException = true;
do {
System.out.println("Enter the divisor: ");
try {
divisor = sc.nextInt();
checkException = true;
}
catch (InputMismatchException e)
{
System.out.println("Invalid data. Please enter an integer.");
sc.next();
}
catch (ArithmeticException e)
{
System.out.println("Invalid data. Please enter an integer other than 0.");
sc.next();
}
} while (checkException == false);
result= division (numerator, divisor);
System.out.println(numerator+"/"+divisor+"="+result);
}
}