0

我不知道为什么我没有得到预期的结果!我把预期的结果写在了最后。好吧,我有两个类:CalculatorEngineCalculatorInput,前者计算,而后者给出一个行模式接口。的代码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功能无法正常工作。帮助!

4

2 回答 2

4

改变这个:

if (c == '0' && c <= '9')

对此:

if (c >= '0' && c <= '9')

否则,只有当 c 为 时才会成立'0'

于 2012-10-26T12:52:56.363 回答
2
else if (c == '0' && c <= '9') engine.digit(c - '0');

如果 c 不等于 0 则为假..

于 2012-10-26T12:55:13.347 回答