How to get divide and modulo method to not print the 'return 0' to output


The following is my code for the divide method:

1 public int divide(int a, int b){
2 if(b == 0)
3 {
4 System.out.println(“System Error”);
5 return 0;
6 }
7 else
8 {
9 return (a / b);
10 }
11 }

The following is what outputs to the screen from these lines of code:

1 System Error
2 0

I understand that a 0 needs to be returned as I have specified a return type, but is there a way to have the ‘0’ in line 2 of the output not appear? If I just want the screen to output only ‘System Error’ can I do this without changing the return type of the method?


returning from a method doesn’t cause the return value to be written to System.out (and if you made that assumption you should revisit that and figure out where you went wrong in your reasoning), so your code already satisfies what you want it to (not) do

Note that 0 could be the result of division, so the caller has no way of telling if something went wrong (unless they too check if the divisor is 0 but that would be doing it twice) so this error handling scheme is flawed


I see what you’re saying now. Thanks!


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.