0

So I am reworking my java beginner "Divide" program, where you have to divide two integers inputted by user. My problem is when inputting an alphabet or symbol, i get an infinite loop. The catch seems to work fine (output reads error) but it's a loss after that. Here is the code. Any help would be greatly appreciated.

 public class Divide
{  
    public void Divide (int num1, int num2) throws NegativeNumberException {

    }

public static void main (String[] args) throws ArithmeticException, InputMismatchException
    {

   int num1 = 0;
   int num2 = 0;
   double ratio;
   Scanner scan = new Scanner(System.in);
   int looper = 0; //using variable for do-while loop

   do { //re-runs code if input error
   try {
   System.out.println("Let's divide some numbers!"); 
   System.out.print("Enter your first whole number: ");
   num1 = scan.nextInt();
   System.out.print("Enter your second whole number: ");
   num2 = scan.nextInt();

    if (num1 < 0 || num2 < 0) {
           throw new NegativeNumberException("No Negative Numbers Allowed.");
        }
    else if (num1 == 0 || num2 == 0) {
            throw new ArithmeticException();
    }

   } 

    catch(InputMismatchException a) {
     System.out.println("Wrong input: " + a.getMessage());
     continue;

    }

   catch(ArithmeticException ae){
     System.out.println("Error:"+ ae.getMessage());
     System.out.println("No zeroes!");
     continue;
     }

   catch (Exception c) { 
     System.out.println("This won't work." + c.getMessage());
     scan.nextLine();
     continue;

    }

    ratio = (double)num1 / num2;
   System.out.println("The answer is: " + ratio);
    looper = 1; //when complete, this change will end program

    }while (looper == 0);
}
}
Michael Lewis
  • 77
  • 1
  • 1
  • 6
  • 1
    scan.nextInt() doesn't discard the input if it fails to match an integer, so you'll need to use scan.nextLine() to consume it. – tgdavies Nov 21 '19 at 00:42
  • sorry, I'm not seeing where you're talking about. initial input would be type int and the call in the catch doesn't change anything, even after putting in nextLine – Michael Lewis Nov 21 '19 at 01:30
  • 1
    @MichaelLewis You only have `nextLine()` in the `Exception` catch block. In the case of `InputMismatchException` (when the input is **not** an `int`), you don't consume the input which was not an `int`. – Elliott Frisch Nov 21 '19 at 01:31
  • it finally clicked. Thanks everyone – Michael Lewis Nov 21 '19 at 02:31

0 Answers0