-2

I am learning this simple code but I do not understand why b do not return the value of the division. For example I input 10 and 2 and it output for me 2 instead of 5.

Thanks for your time!

    import java.util.Scanner;
class Throw_Exception{
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int a = 0;
        
        do{
        System.out.println("Input number A and B: ");
        a = input.nextInt();
        int b = input.nextInt();
        input.close();
        div(a,b);
        System.out.println("The division is " + b);
    }while (a != -1 );
}

    static int div(int a, int b) throws ArithmeticException{
        if(b == 0){
            throw new ArithmeticException("Division by Zero");
        }else{
            b = a/b;
            return b;
        }
    }
}
Fefs
  • 11
  • 3
  • 2
    You do nothing with the value returned by `div(a, b)`. It is immediately discarded. Also, your `b` on the outside will not be changed by that method, because Java is pass-by-value. You need to reassign the result: `b = div(a, b)` – QBrute Aug 05 '21 at 14:28
  • The `b` from `div` is in no way connected to the `b` from your `div(a,b)` call. Learn about variables and their scopes. Those are two completely different variables that just happen to have the same name. – Zabuzard Aug 05 '21 at 14:30
  • It appears you misunderstand how `return b;` works. It makes `b` the value of the expression `div(a, b)`. So if you want to change the value of `b`, assign it: `b = div(a, b);`. And note that there are two variables named `b` here, in different scopes. – Fred Larson Aug 05 '21 at 14:31
  • 1
    Your `div` method is overly complex. In fact, it is obsolete. Java already checks for division with zero and throws this exception automatically. So you can in fact just remove the method completely and write `b = a / b;` in your `main` method and it will have the exact same behavior. – Zabuzard Aug 05 '21 at 14:31

1 Answers1

3

You're ignoring the result returned by div(a,b). you need to assign the value to b:

b = div(a,b);
devReddit
  • 2,696
  • 1
  • 5
  • 20