Java除以零 - 计算器

时间:2018-02-27 17:59:03

标签: java division arithmetic-expressions

我已经创建了一个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
}

}

2 个答案:

答案 0 :(得分:2)

您只需将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;
    }
}

答案 1 :(得分:2)

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

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;
    }
}
相关问题