2011-10-12 50 views
0

所以我的計算器,涉及到兩位數,包括但C按鈕任何計算完美的作品,如果我嘗試任何三個數字計算,這並不真的如工作1 + 2 + 3 = 5會有人告訴我爲什麼是這樣,無論如何我可以修復它?計算器解決三位數不能正常工作

public class Calculator { 

    private long currentInput;   //current input 
    private long previousInput;   // previous input 
    private long result;   // result of calculation 
    private String lastOperator = ""; // keeps track of the last operator entered 


    /* New digit entered as integer value i - moves currentInput 1 decimal place to the left and adds i in "one's column" */ 
    public void inDigit(long i) { 
    currentInput = (currentInput * 10) + i; 
    } 


    /* Operator entered + - or * */ 
    public void inOperator(String op) { 
    previousInput = currentInput;  // save the new input as previous to get ready for next input 
    currentInput = 0; 
    lastOperator = op;     // remember which operator was entered 
    } 


    /* Equals operation sets result to previousInput + - or * currentInput (depending on lastOperator) */ 
    public void inEquals() { 
    if (lastOperator.equals("+")) { 
     result = previousInput + currentInput; 
    } else if (lastOperator.equals("-")) { 
     result = previousInput - currentInput; 
    } else if (lastOperator.equals("*")) { 
     result = previousInput * currentInput; 
    } 
    lastOperator = "";  // reset last operator to "nothing" 
    } 


    /* Clear operation */ 
    public void inClear() { 
    currentInput = 0; 
    previousInput = 0; 
    result = 0; 
    lastOperator = ""; 
    } 

    /* returns the current result */ 
    public String getResult() { 
    return Long.toString(result); //converts int to String 
    } 

    /* returns the previous input value */ 
    public String getPreviousInput() { 
    return Long.toString(previousInput); 
    } 
    /* returns the current input value */ 
    public String getCurrentInput() { 
    return Long.toString(currentInput); 
    } 

回答

3

好吧,你只存儲最後兩個操作數,所以你的例如1 + 2 + 3 = 5,當你進入第二個+號1丟失,2 + 3 = 5因爲在你的InEquals。

1

()方法,你只用previousInput和currentInput所以你的1 + 2 + 3 = 5,因爲第二個 '+' 結果= 2 + 3

3

只儲存最後兩「輸入」進入(在previousInputcurrentInput),所以當你去到三個或更多的操作數不先擊中=,所有,但最近一消失。

2

你的問題是當你添加一個新的操作符時,你只需要將你的值移出去做任何計算,如果存儲了前一個操作符,並且在添加新操作符時設置了這兩個值,則需要對現有值進行計算,操作員在更換存儲的操作員之前