-3

My program takes input from a user, first number, operation ( + - * / ^) then a second number. When I enter 5 / 0 it says ERROR!!! Cannot divide by 0 . That's what its supposed to do. However, When I type in 5 / 5 which is 1 I get my error message.

do {
    try {
        if (opperation == "/" && num2 == 0);
        throw new ArithmeticException();
    } catch (ArithmeticException ae) {
        System.out.println("ERROR !!! Cannot divide by 0");
    }
    System.out.println("Enter First Number");
    num1 = scan.nextInt();
    System.out.println("ENTER Opperation: ");
    opperation = scan.next();
    System.out.println("ENTER Second Number: ");
    num2 = scan.nextInt();
} while (num2 == 0);
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Tyler Pierog
  • 527
  • 5
  • 15

2 Answers2

2

You have a stray semicolon in your if-statement. It should be

if (opperation == "/" && num2 == 0)
    throw new ArithmeticException();

instead of

if (opperation == "/" && num2 == 0);
    throw new ArithmeticException();

What you have is basically the same thing as

if (opperation == "/" && num2 == 0) {

}
throw new ArithmeticException();
Dennis Meng
  • 5,109
  • 14
  • 33
  • 36
1

You shouldn't have a semicolon after your if statement. This makes the body of the if statement into nothing. Change it to this:

if (opperation == "/" && num2 == 0)
    throw new ArithmeticException();

Your IDE seems to have caught this and reindented the code for you, in the wrong way.

By the way, that isn't how you use ArithmeticException. A line of code that divides by 0 will automatically throw an ArithmeticException, and you can catch it then. However, that is slower than not using ArithmeticException at all:

if (opperation == "/" && num2 == 0)
    System.out.println("ERROR !!! Cannot divide by 0");
tbodt
  • 16,609
  • 6
  • 58
  • 83