Question about .divide method - Basic Calculator project


#1

Hello

I´ve finished the “Basic Calculator” project, but i have a question about the .divide method

First, here´s my code:

class Calculator{

public Calculator(){

}

public int add(int a, int b){
return a + b;
}

public int subtract(int a, int b){
return a - b;
}

public int multiply(int a, int b){
return a*b;
}

public int divide(int a, int b){

if( b == 0) {
  
  System.out.println("Error! Dividing by zero is not allowed.");
  
  return 0;
  
} else{
   
  return a / b;
  
}

}

public int modulo(int a, int b){

if( b == 0) {
  
  System.out.println("Error! Dividing by zero is not allowed.");
  
  return 0;
  
} else {
  
  return a % b;
}

}

public static void main(String[]args) {

Calculator myCalculator = new Calculator();

System.out.println(myCalculator.add(5,7));

System.out.println(myCalculator.subtract(45,11));

System.out.println(myCalculator.divide(5,0));

}
}

I don´t understand why we have to return 0 (zero), inside the “if”, after we print out the Error message.

any thoughts?

thanks


#2

Hey Pedro!!

I’m not a coding expert, but I can tell you it’s because there needs to be a value assigned!!
If you just print the zero and don’t have a value assigned, you will get an error on the code.

Someone correct me if I am wrong, but I’m positive I am correct.


#3

hey

thanks for your reply, i was asking because i believed it should not output 0, when we are dividing some number by zero. Any calculator will only give you an error, if one tries to divide a number by zero.


#4

Yes! But since the code requires a Integer to be returned, a value must be returned.
Fully agree with you, as I thought the same thing when I was on this one!


#5

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