将字符推入堆栈会改变它来自的字符串吗?

时间:2016-03-03 22:29:59

标签: java stack substring postfix-notation infix-notation

我有一个hw赋值,要求将中缀表达式转换为后缀表达式。

编辑: 假设发生了什么:    输入:(5)输出:5;输入:(1 + 1)输出:11+;输入=((9/3)-2) 输出= 93 / 2- 这段代码会发生什么:输入:(5)(代码保持运行)

我调试了它,问题似乎是我的第二次循环。它只是保持循环,我不确定为什么。我认为将子字符串推入堆栈会更新循环并将字符串从(5)更改为5)

// data fields 
   StackInterface<String> stack = new ArrayStack<String>();
   String output = "";
   int first = 0;
   int second = 1;
   String oneChar = infixExpression.substring(first,second);

  //while   
  while (infixExpression.length()>0){
     while(oneChar.equals("(")){
         stack.push(oneChar);
         first ++; 
         second ++;
       }
       //if char is ), pop off stack while char is not (
       //add to string operators, add to output
        while(oneChar.equals(")")){
         while (oneChar != "(" && stack.empty() == false){
         String popOperator = stack.pop();
          output = output + popOperator;

         //moves to next char of String  
           first ++; 
           second ++;

         }//end of while loop

         }
         while((oneChar == "*") || (oneChar == "/") || (oneChar == "%") || (oneChar == "+") ||(oneChar == "-")){

          stack.push(oneChar);

         //moves to next char of String  
           first ++; 
           second ++;
          } 
         //error checking input is int
         try{

            Integer.parseInt(oneChar);
             output = output + oneChar;

          //moves to next char of String  
             first ++; 
             second ++;
         } catch (InputMismatchException e){
          System.out.print("Not a valid expression"); 
          }
         }//end of while loop
     System.out.print("Postfix Expression: " + output);

}

1 个答案:

答案 0 :(得分:0)

  

将字符推入堆栈会改变它来自的字符串吗?

没有。在我之后重复......“字符串是不可变的。它们不能改变。”

查看代码,算法级别似乎存在一些主要问题。提示:您不应该需要一个四深嵌套循环来处理括号。在顶级循环中,逻辑应该是这样的:

if operand then do something, 
else if operator then do something, 
else if '(' then do something, 
else if ')' then do something, 
else error.