Java 除以零 - 计算器

Java Divide by Zero - Calculator

我创建了一个 Java 计算器,但是我需要添加代码,以便在数字除以零时将结果设置为零。其他一切正常我只是不知道在哪里添加这个声明。

代码如下:

public class Calculator
{
// Declaration of a long variable to hold the stored result

private long theResult = 0;  
private long zero = 0;

// Evaluate an arithmetic operation on the stored result
//  E.g evaluate( '+', 9) would add 9 to the stored result
//      evaluate( '/', 3) would divide the stored result by 3
//      actions are '+'. '-', '*', '/'
// Note: if the operation is
//      evaluate( '/', 0 ) the theResult returned must be 0
//      (Not mathematically correct)
//      You will need to do a special check to ensure this
/**
 * perform the operation 
 *  theResult = theResult 'action' number
 * @param action An arithmetic operation + - * /
 * @param number A whole number
 */
public void evaluate( char action, long number)
{

    if (action == '+'){
        theResult += number;
    }

    else if (action == '-'){
        theResult -= number;
    }

    else if (action == '*'){
        theResult *= number;
    }


    else if (action == '/'){
        theResult /= number;
    }


}



/**
 * Return the long calculated value
 * @return The calculated value
 */
public long getValue()
{
    return theResult;
}

/**
 * Set the stored result to be number
 * @param number to set result to.
 */
public void setValue( long number )
{
    this.theResult = number;
}

/**
 * Set the stored result to be 0
 */
public void reset()
{
    if ( theResult != 0) theResult = 0; 
    // im not sure this is correct too
}

}

您只需在现有语句中嵌套一个 if 语句,如下所示:

 else if (action == '/'){
    if (number == 0){ //this is the start of the nested if statement
       theResult = 0; //alternatively, you can just type "continue;" on this line since it's 0 by default. 
    }
    else {
       theResult /= number;
    }
}

有两种方法可以做到这一点。第一个是这样的:

else if (action == '/') {
    if( number == 0 )
        theResult = 0;
    else
        theResult /= number;
}

另一个选项假定您已经了解异常:

else if (action == '/') {
    try {
        theResult /= number;
    }
    catch( ArithmeticException ae ) {
        // possibly print the exception
        theResult = 0;
    }
}