2012-10-26 2 views
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의 코드는 다음과 같이 진행됩니다

[0]1 
[1]3 
[13]+ 
[0]1 
[1]1 
[11]= 
[24] 

:

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 
[0]3 
[0]+ 
[0]1 
[0]1 
[0]+ 
[0] 

digit과 같은 기능이 제대로 작동하지 않습니다. 도움!

+0

당신이 일이 같은 것을 1 + 2로 입력을주는 샘플 입력을 추가 + –

답변

4

변경이 : 여기에

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

는 : C가 '0'

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

그렇지 않으면, 그것은 단지 사실 일 것입니다.

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

하지 동일의 c 0의 거짓 ..

관련 문제