所以我的计算器可以完美地处理涉及两个数字的任何计算,包括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);
}
答案 0 :(得分:3)
嗯,你只存储了最后两个操作数,所以对于1 + 2 + 3 = 5的例子,当你输入第二个+号时,1会丢失,而2 + 3 = 5。
答案 1 :(得分:3)
您只存储输入的最后两个“输入”(在previousInput
和currentInput
中),这样当您在没有先点击=
的情况下转到三个或更多操作数时,除了最新的两个消失了。
答案 2 :(得分:2)
你的问题是当你添加一个新的操作符时你只需要移动你的值而不进行任何计算,如果存储了前一个操作符并且在添加新操作符时设置了两个值,则需要对现有值和运算符进行计算在更改存储的运算符之前
答案 3 :(得分:1)
因为在你的InEquals()方法中,你只使用previousInput和currentInput,所以你的1 + 2 + 3 = 5因为第二个'+'结果= 2 + 3