Hello! I am new in java and I have this code that will throw an exception if the numerator input is not an integer and will stop the loop process when the user input 'e' as its numerator. Thank you for your help in advance.

package org.alibata.training.codes.exceptions;

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

public class TrapDivide {

    public static void main(String[] args){

        TrapDivide trapDiv = new TrapDivide();
        Scanner scan = new Scanner(System.in);
        int quo;
        int num = 1;
        int den;
        int c = (char)'e';

        while(num != c){
        System.out.println("Enter the numerator: ");
        num = scan.nextInt();
        System.out.println("Enter the denominator: ");
        den = scan.nextInt();

            try {
                quo = trapDiv.divIntegers(num, den);
                System.out.println(num + " /" + den + " is " + quo);

            } catch (NotValidNumeratorException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            } catch (NotValidDenominatorException e) {
                System.out.println( );
                e.printStackTrace();

            } catch (InputMismatchException ex) {
                System.out.println("wrong");


            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }

    public int divIntegers(int num, int den)throws NotValidNumeratorException, NotValidDenominatorException, Exception{


        if(num == 0){
            throw new NotValidNumeratorException();

        } else if(den == 0){
            throw new NotValidDenominatorException();

        } 

        return num / den;   

    }

}

You should always include the output you get from runnnig the code so that you can get better answers. Regarding your question, nextInt throws an Exception when the next token is not an int. Two solutions here:

  1. Check if the next token is an integer before calling nextInt on the scanner. The method you are looking for is hasNextInt
  2. Trap the Exception you get from nextInt and repeat the loop till you get a valid integer input from the user

I would personally go with (1) inside a loop.

While (1) would be the obvious choice in real-life code, this code looks very much like an exercise in exception handling, so option (2) seems the one that is expected. The try/catch is already in place, so it just needs some code to loop until no exception is caught.

This article has been dead for over six months. Start a new discussion instead.