簡體   English   中英

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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM