在java中制作计算器

时间:2012-10-26 12:49:04

标签: java

我不知道为什么我没有得到预期的结果!我最后写了预期的结果。好吧,我有两个类: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功能无法正常工作。救命啊!

2 个答案:

答案 0 :(得分:4)

改变这个:

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

对此:

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

否则,只有当c为'0'时才会出现。

答案 1 :(得分:2)

else if (c == '0' && c <= '9') engine.digit(c - '0');

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