Reputation: 2285
In this function I need two different datatype for return, one float when y
is not zero and a Boolean when it's zero.
public XXXXX division(int x, int y){
if(y!=0){
return x/y;
}
else{
return false;
}
}
I know that I can implement this with using two function 1- check correction of division 2- calculate the correct division what I want it in One function, It's possible?
Upvotes: 0
Views: 173
Reputation: 6079
You can check if the value of Y
is zero or not before calling the function itself. Don't allow zero to be passed to that function.
And anyway if you pass zero to the function divide by zero situation will throw ArithmaticException
. So your function can throw that exception to the caller.
public float division(int x, int y) throws Exception { ///ArithmaticException
return ((float) x) / y;
}
Upvotes: 2
Reputation: 691715
Passing 0 as divisor shouldn't be allowed. You should throw an exception instead of returning false in this case:
public float division(int x, int y) {
if (y != 0) {
return ((float) x) / y;
}
else {
throw new IllegalArgumentException("division by 0 makes no sense");
}
}
Upvotes: 5
Reputation: 621
Maybe you should check it prior:
Pseudocode
if(y!=0){
get division(x/y)
}else{
say Cannot divide by 0
}
Upvotes: 1
Reputation: 500307
You could return Float
, using null
signify "no result":
public Float division(int x, int y) {
if(y != 0) {
return x / (float)y;
} else {
return null;
}
}
That said, in this particular case it might actually make sense to return IEEE infinity or NaN.
Note that I've fixed the integer division as it sounds that this isn't what you want.
Upvotes: 1
Reputation: 4202
The simplest way-
public Object division(int x, int y) {
if (y != 0) {
return x / y;
} else {
return false;
}
}
Upvotes: 1
Reputation: 223237
Not really sure if it is a good practice to have a single method for something like that. But you can create your own class with result and error as property and then return object of that class from your method.
Upvotes: 2
Reputation: 410
Maybe use a Double as a return type and return the value normally. In case of false, return null.
Upvotes: 1