检查堆栈中的元素是数字还是运算符?

时间:2017-10-31 01:38:54

标签: java iterator stack rpn

我正在尝试使用扫描仪创建RPN计算器。我从用户那里收集数字和运算符,并将输入连接到一个名为results的字符串上。一旦他们退出(通过说" Q"或" q"),我想将results传递给方法evaluateResults,这将执行他们的操作inputed。例如,如果传递给evaluateResults的字符串是' 45 +',我想添加4和5.但是,如果输入是' 456 + x&#39 ;我想表演'(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);
      }
    }
  }
}

我遇到的问题是我无法通过使用迭代器在堆栈的开头添加int output。如何修改此代码以执行我上面描述的方法?任何修改都会有所帮助,如果我不清楚任何事情,请告诉我,我会澄清。

1 个答案:

答案 0 :(得分:0)

这里是解释RPN的基本过程,用伪代码描述:

.page-template-page-services-new .imgBlock:hover { .page-template-page-services-new .ButtonService {color: #6395ce; background-color: #fff; } }