2016-03-03 45 views
0

我有一个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); 

}

+0

你说你不认为你做得对。如果您向我们提供了几个您正在为此代码提供的表达式来测试它的示例,那么您的代码是什么与您期望它执行的操作有什么关系。参见[如何提出一个好问题](http://stackoverflow.com/help/how-to-ask)。 –

回答

0

是否推字符到堆栈改变它来自字符串?

不需要重复......“字符串是不可改变的,它们不能改变。”


看看你的代码,算法级别似乎存在一些主要问题。提示:您不应该需要四深度嵌套循环来处理括号。在最高级别的循环中,您应该使用如下逻辑:

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

我认为你需要向后退一步,并试着理解你正试图实现的算法。从铅笔和纸开始,“手工”。一旦你清楚地理解了算法,那么你可以尝试用Java编写它。但显然,你不能更新字符串的值,因为字符串不能被改变。 –