1

I have the following method in a Java program:

public void Div(int a, int b){
            //exception in order to check if the second argument is 0
            try{
                int div1 = (a / b);
                double div = div1;
                System.out.println("The division of the two numbers is: " + div);
            }
            catch(ArithmeticException e){
                System.out.println("You can't divide a number by 0");
            }

This only works if numerator is larger than the denominator ( e.g 8/2). If the numerator is smaller than the denominator I get a result of 0.0 (e.g. 2/8).

What can I do to make it work?

user47
  • 141
  • 7
  • 3
    use other datatypes then int. int are only whole numbers, no decimals. change a, b and div1 into float or double – Stultuske Apr 16 '20 at 07:14

2 Answers2

1

It's happening because of integer division. You can cast one of the arguments to double and store the result to a double variable to fix the issue.

public class Main {
    public static void main(String[] args) {
        div(5, 10);
    }

    public static void div(int a, int b) {
        try {
            double div = (double) a / b;
            System.out.println("The division of the two numbers is: " + div);
        } catch (ArithmeticException e) {
            System.out.println("You can't divide a number by 0");
        }
    }
}

Output:

The division of the two numbers is: 0.5

On a side note, you should follow Java naming conventions e.g. the method name, Div should be div as per the Java naming conventions.

halfer
  • 19,824
  • 17
  • 99
  • 186
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

(a/b) You're doing integer division. You need to typecast to other data types that can store decimal like double.

 double div = (double) a / b;
backdoor
  • 891
  • 1
  • 6
  • 18