-6

How do I make my program to not allow the user to divide by zero? If you divide by zero the program will handle the exception and display message “Please input another integer than zero" using try and catch

import java.util.*;

public class Calculation {
  public static void main(String args[] ){
    Scanner s = new Scanner(System.in);
    int num1 = 0, num2 = 0, answer;
    try {
      if (num1 == 0) {
        System.out.print("Enter first integer to be divided: ");
        num1 = s.nextInt();
        System.out.println("Please input another integer than zero");
      } else if (num2 == 0) {
        System.out.print("Enter second integer to be divided: ");
        num2 = s.nextInt();
        System.out.println("Please input another integer than zero");
      } else {
        answer = num1/num2;
        System.out.println("Answer is: " + answer );
      }
    } catch(Exception e) {
      System.out.println("Answer is: " + e.getMessage());
    }
  }
}
nabskim
  • 9
  • 1
  • 7

1 Answers1

0

Simply throw-catch an Exception such as proposed ArithmeticException or create your own:

try {
    if(num2 == 0){
        throw new ArithmeticException();
    }
} catch (ArithmeticException e) {
    System.out.println("Please input another integer than zero");
}
Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109