【问题标题】:Java Divide by Zero - CalculatorJava 除以零 - 计算器
【发布时间】:2018-08-07 11:29:27
【问题描述】:

我创建了一个 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。检查除数是否为0。如果是,则结果为0。否则,进行除法。
  • 编辑后,在实际分割完成之前,它会在块if (action == '/') {...}中。
  • 我将如何检查是否有人在这里除以零
  • 检查输入或捕获异常(ArithmeticException)

标签: java division arithmetic-expressions


【解决方案1】:

您只需在现有的语句中嵌套一个 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;
    }
}

【讨论】:

    【解决方案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;
        }
    }
    

    【讨论】:

    • 我还没有了解异常,但这是之前出现在错误消息中的内容,因此尝试查看它,谢谢,这也是有道理的
    猜你喜欢
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多