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

/**
 * Illustrates the need for exceptions to handle input such as: 7, seven, and dividing by 0
 */
public class DivideTwoNumbers01{

    public static int getInt(Scanner scanner, String prompt){
        boolean success = false;
        do{
            System.out.print(prompt);
            try{
                return scanner.nextInt();
            }catch(InputMismatchException e){
                System.err.println("Sorry, that isn't a valid whole number.");
                String garbage = scanner.next();
                System.err.println("DEBUGGING: garbage: " + garbage);
            }catch(NoSuchElementException e){
                System.err.println("Sorry, I needed more inputs.");
                System.exit(1);
            }
        }while(success == false);
        return -1;
    }

    public static void main( String[] args ){
        Scanner stdinScanner = new Scanner( System.in );
        int num1 = 0;
        int num2 = 0;
        int result = 0;
        boolean success = false;
        // get two numbers from the user
        num1 = getInt( stdinScanner, "Please enter a number: ");
        do{
            num2 = getInt( stdinScanner, "Please enter another number: ");

            // calculate the result
            try{
                result = num1 / num2;
                success = true;
            }catch(ArithmeticException err){
                System.err.println("Sorry, I can't divide by zero.");
            }
        }while(success == false);

        // display the result
        System.out.println( num1 + " divided by " + num2 + " equals " + result);
    }
}