Here is problem in a nut shell. I have made a basic caluclator in java but I am trying to getting the calculator to return 0 when a number is entered and it is divided by 0. Each time I keep getting an error message!
class Calculator
{
long sum;
public void evaluate( char action, long number )
{
if (action == '+')
{
sum = number + number;
}
if (action == '-')
{
sum = number - number;
}
if (action == '*')
{
sum = number * number;
}
if (action == '/')
{
sum = number / number;
}
**if (sum == number / 0)
{
sum = 0;
}
}**
I'd just add this logic to your division code:
ReplyDeleteif (action == '/')
{
if (number == 0)
{
sum = 0;
} else {
sum = number / number;
}
}
Also, why are you using the same number per operation? The subtraction operator will always return 0. If you are using this code in a calculator, just check whether the denominator is 0.
if (action == '/')
ReplyDelete{
if(number2 == 0)
{
System.out.println("You cannot divide by 0!");
return;
}
sum = number1 / number2;
}
With ternary operator:
ReplyDeleteif (action == '/') {
sum = number == 0 ? 0 : number / number; // <-- isn't that just 1 ?
}
The IEEE 754 standard includes not only positive and negative numbers that consist of a sign and magnitude, but also positive and negative zeros, positive and negative infinities, and special Not-a-Number values (hereafter abbreviated NaN). A NaN value is used to represent the result of certain invalid operations such as dividing zero by zero. NaN constants of both float and double type are predefined as Float.NaN and Double.NaN.
ReplyDeleteYou need to add condition make sure you are not dividing by ZERO.
if(secondnumber == 0)
{
return;
}
Just for the sake of completeness, why not catch the exception (and use java coding conventions) ?
ReplyDeleteif (action == '/') {
try {
sum = number / number;
catch (ArithmeticException e) {
//log error
sum = 0;
}
}
The bonus here is that it handles whatever else wrong could happen.