Note that there are some explanatory texts on larger screens.

plurals
  1. POConverting_infix_expressions_to_postfix_expressions
    text
    copied!<p>I thought that this code should solve the problem with inputs with parentheses like </p> <pre><code>1 * 2 + 3 * ( 5 + 2 ) - 3 </code></pre> <p>and output the postfix expression without parentheses, but the output is </p> <pre><code>1.0 2.0 * 3.0 * + 5.0 2.0 + ( 3.0 - ) </code></pre> <p>and another example: </p> <pre><code>9 - 5 * 8 + 19 - ( 8 + 10 ) </code></pre> <p>will be: </p> <pre><code>9.0 5.0 8.0 * - 19.0 + - 8.0 10.0 + ( ) </code></pre> <p>So I want to know why this code can't handle this case. I want the return string without parentheses by a good manner without deleting the parentheses at the end of the expression. </p> <pre><code>public static String Converting_infix_expressions_to_postfix_expressions(String infix) throws Exception{ StringTokenizer st = new StringTokenizer(infix); int numOF_tokens = st.countTokens(); String postfix = "" ; for (int i = 1; i &lt;= numOF_tokens; i++) { String term = st.nextToken(); try { // if it is an Float there is no problem will happen float x = Float.parseFloat(term); postfix += x +" " ; } catch (Exception e) { if(stack.isEmpty()) stack.push(term); else if(term == "(") stack.push(term); else if(term == ")"){ while(!stack.isEmpty() &amp;&amp; (String)stack.peek() != "(") postfix += stack.pop() +" "; stack.pop(); } else{ int x = 0,y = 0; switch(term){ case "+": x = 1; break; case "-": x = 1; break; case "*": x = 2; break; case "/": x = 2; break; } switch((String)stack.peek()){ case "+": y = 1; break; case "-": y = 1; break; case "*": y = 2; break; case "/": y = 2; break; } if(x &gt; y) stack.push(term); else { int x1 = x , y1 = y; boolean puchedBefore = false; while(x1 &lt;= y1){ //when the operator in the peak of the stack is smaller than one read before from the infix excepression. postfix += stack.pop() +" "; if(stack.isEmpty() || stack.peek() == "(" ){ // to put the term in it's right place if it samller than all the previos operators until the begining of this subset excepression "if it is between parentheses or not " stack.push(term); puchedBefore = true; break; } else{ switch(term){ case "+": x1 = 1; break; case "-": x1 = 1; break; case "*": x1 = 2; break; case "/": x1 = 2; break; } switch((String)stack.peek()){ case "+": y1 = 1; break; case "-": y1 = 1; break; case "*": y1 = 2; break; case "/": y1 = 2; break; } } } if(!puchedBefore) stack.push(term); } } } } while (! stack.isEmpty ()) { postfix += stack.pop () + " "; } System.out.println ("The postfix expression is : " + postfix); return postfix; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload