2017-10-31 9 views
0

스캐너를 사용하여 RPN 계산기를 만들려고합니다. 사용자로부터 숫자와 연산자를 수집하고 입력을 results이라는 문자열에 연결합니다. "Q"또는 "q"라고 말하면서 종료하면 resultsevaluateResults 메서드에 전달하여 입력 한 작업을 수행합니다. 예를 들어, evaluateResults에 전달 된 문자열이 '45 + '인 경우 4와 5를 추가하고 싶습니다. 그러나 입력이'456 + x '인 경우'(4 + 5) x 6 '을 수행하고 싶습니다.스택의 요소가 숫자인지 또는 연산자인지 확인하십시오.

import java.util.*; 

/** 
    This calculator uses the reverse Polish notation. 
*/ 
public class P15_7 { 

    public static void evaluateResult(String inp){ 
    int output = 0; 
    Stack<Integer> results = new Stack<>(); 
    for (int i = 0; i < inp.length(); i++){ 
     char c = inp.charAt(i); 
     if (Character.isDigit(c)){ 
     results.push(Character.getNumericValue(c)); 
     }else{ 
     Iterator<Integer> itr = results.iterator(); 
     while(itr.hasNext()){ 
      if (c == '+'){ 
      int f = itr.next();  // Getting the First value of the Stack 
      itr.remove();    // Removing it (first val) 
      int s = itr.next();  // Getting the Second value of the Stack 
      itr.remove();    // Removing it (second val) 
      output = output + (f + s);// calculate 
      itr = results.iterator(); // Starting the iterator back at Index 0 
      itr.add(output);   // Adding the calculated value at the start : Index 0 
      }else if (c == '-'){ 
      int f = itr.next(); 
      itr.remove(); 
      int s = itr.next(); 
      itr.remove(); 
      output = output + (f - s); 
      itr = results.iterator(); 
      itr.add(output); 
      }else if (c == '*' || c == 'x'){ 
      int f = itr.next(); 
      itr.remove(); 
      int s = itr.next(); 
      itr.remove(); 
      output = output + (f * s); 
      itr = results.iterator(); 
      itr.add(output); 
      }else if (c == '/'){ 
      int f = itr.next(); 
      itr.remove(); 
      int s = itr.next(); 
      itr.remove(); 
      output = output + (f/s); 
      itr = results.iterator(); 
      itr.add(output); 
      } 
     } 
     } 
    } 
    System.out.println("You answer is: " + output); 
    } 
    public static void main(String[] args) { 
    Scanner in = new Scanner(System.in); 
    String results = ""; 
    System.out.println("Enter one number or operator per line, Q to quit. "); 
    boolean done = false; 

    while(!done){ 
     String input = in.nextLine(); 
     if(input.equals("Q") || input.equals("q")){ 
     evaluateResult(results); 
     done = true; 
     }else{ 
     results = results.concat(input); 
     System.out.println(results); 
     } 
    } 
    } 
} 

: 캐릭터가 운영자 때까지 내가 문자열을 읽고있다 의미, 그때는 문자열의 처음 두 숫자와 그 연산자를 수행 ... 나는 다음과 같은 프로그램이 작업을 수행하려고 시도하고있다 내가 실행중인 문제는 itterator를 사용하여 스택의 처음에 추가 할 int를 얻을 수 없다는 것입니다. 위에서 설명한 방법을 수행하기 위해이 코드를 수정하려면 어떻게해야합니까? 어떤 수정 사항이 도움이 될 것입니다 그리고 내가 무엇에 대해 불분명한지 알려 주시면 분명히하겠습니다.

+1

귀하의 개념이 올바르지 않습니다. RPN에서는 먼저 '4 11 x', 그 다음 '44'로 평가됩니다. –

+0

스택 반복자에는'add' 메소드가 없습니다. 코드는 현재 형식으로 컴파일되지 않습니다. – jrook

+0

iterator를 사용하여 기본 컬렉션에 요소를 추가 할 수 없습니다. 'remove()'의 사용조차 때때로 [여기] (https://stackoverflow.com/questions/11196561/why-there-is-no-add-method-initerator-interface)에서 눈살을 찌푸리게됩니다. – jrook

답변

0

여기 의사에 설명 된 RPN을 해석하는 기본 과정입니다 :`456 + x` 무엇을 의미하는지

while (more input available) 
{ 
    get next input synbol S 
    if (S is a number) 
     push S on the Stack 
    else // S must be an operator 
    { 
     pop the top item from Stack into op2 
     pop the (new) top item from Stack into op1 
     compute the result R by performing the operation named by S 
      on op1 and op2 
     push R on the stack 
    } 
} 
pop the final result from the Stack