我不知道为什么我没有得到预期的结果!我把预期的结果写在了最后。好吧,我有两个类:CalculatorEngine
和CalculatorInput
,前者计算,而后者给出一个行模式接口。的代码CalculatorEngine
是这样的,没什么花哨的:
public class CalculatorEngine {
int value;
int keep;
int toDo;
void binaryOperation(char op){
keep = value;
value = 0;
toDo = op;
}
void add() {binaryOperation('+');}
void subtract() {binaryOperation('-');}
void multiply() {binaryOperation('*');}
void divide() {binaryOperation('/');}
void compute() {
if (toDo == '+')
value = keep + value;
else if (toDo == '-')
value = keep - value;
else if (toDo == '*')
value = keep * value;
else if (toDo == '/')
value = keep/value;
keep = 0;
}
void clear(){
value = 0;
keep = 0;
}
void digit(int x){
value = value*10 + x;
}
int display(){
return (value);
}
CalculatorEngine() {clear();} //CONSTRUCTOR METHOD!
}
的代码CalculatorInput
是这样的:
import java.io.*;
public class CalculatorInput {
BufferedReader stream;
CalculatorEngine engine;
CalculatorInput(CalculatorEngine e) {
InputStreamReader input = new InputStreamReader(System.in);
stream = new BufferedReader(input);
engine = e;
}
void run() throws Exception {
for (;;) {
System.out.print("[" +engine.display()+ "]");
String m = stream.readLine();
if (m==null) break;
if (m.length() > 0) {
char c = m.charAt(0);
if (c == '+') engine.add();
else if (c == '*') engine.multiply();
else if (c == '/') engine.divide();
else if (c == '-') engine.subtract();
else if (c == '=') engine.compute();
else if (c == '0' && c <= '9') engine.digit(c - '0');
else if (c == 'c' || c == 'C') engine.clear();
}
}
}
public static void main(String arg[]) throws Exception{
CalculatorEngine e = new CalculatorEngine();
CalculatorInput x = new CalculatorInput(e);
x.run();
}
}
我希望答案是这样的:
[0]1
[1]3
[13]+
[0]1
[1]1
[11]=
[24]
但我得到了这个:
[0]1
[0]3
[0]+
[0]1
[0]1
[0]+
[0]
似乎digit
功能无法正常工作。帮助!