Skip to main content

trying to get the calculator to return 0 not an error message when a number is divided by 0?



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;

}

}**




Comments

  1. I'd just add this logic to your division code:

    if (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.

    ReplyDelete
  2. if (action == '/')
    {
    if(number2 == 0)
    {
    System.out.println("You cannot divide by 0!");
    return;
    }
    sum = number1 / number2;
    }

    ReplyDelete
  3. With ternary operator:

    if (action == '/') {
    sum = number == 0 ? 0 : number / number; // <-- isn't that just 1 ?
    }

    ReplyDelete
  4. 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.

    You need to add condition make sure you are not dividing by ZERO.

    if(secondnumber == 0)
    {

    return;
    }

    ReplyDelete
  5. Just for the sake of completeness, why not catch the exception (and use java coding conventions) ?

    if (action == '/') {
    try {
    sum = number / number;
    catch (ArithmeticException e) {
    //log error
    sum = 0;
    }
    }


    The bonus here is that it handles whatever else wrong could happen.

    ReplyDelete

Post a Comment

Popular posts from this blog

Slow Android emulator

I have a 2.67 GHz Celeron processor, 1.21 GB of RAM on a x86 Windows XP Professional machine. My understanding is that the Android emulator should start fairly quickly on such a machine, but for me it does not. I have followed all instructions in setting up the IDE, SDKs, JDKs and such and have had some success in staring the emulator quickly but is very particulary. How can I, if possible, fix this problem?