My code successfully converts an infix expression to postfix expression. However, when I enter a number that is more than 1 digit (e.g. 546) I get no spaces between this number and the right operand.
A test run of my code: Input: Enter an expression: (24/4) / (15/3) * 10 - 4 + 2 Output: The Postfix Expression is: 244/ 153/ / 10 * 4 - 2+
I'd like it to be The Postfix Expression is: 24 4/ 15 3/ / 10 * 4 - 2+
This is my code: Please suggest any changes that will allow me to insert spaces in the output.
import java.util.*;
public class PostfixConversion {
public static void main(String args[]) {
System.out.print("Enter an expression: ");
String infix = new Scanner(System.in).nextLine();
System.out.println(convertToPostfix(infix));
}
public static boolean precedence(char first, char second)
{
int v1 = 0, v2 = 0;
//find value for first
if(first == '-' || first == '+'){
v1 = 1;
}else if(first == '*' || first == '/'){
v1 = 2;
}//end if
//find value for second
if(second == '-' || second == '+'){
v2 = 1;
}else if(second == '*' || second == '/'){
v2 = 2;
}//end if
if(v1 < v2){
return false;
}//end if
return true;
}//end precedence method
//converts infix expression into postfix expression
public static String convertToPostfix(String infixExp)
{
String postFix = "The Postfix Expression is: ";
Stack<Character> stack = new Stack<Character>();
char character = ' ';
for(int i = 0; i < infixExp.length(); i++)
{
character = infixExp.charAt(i);
//determine if character is an operator
if(character == '*' || character == '-' || character == '/' || character == '+')
{
while(!stack.empty() && precedence(stack.peek(), character)){
postFix += stack.pop();
}//end while
stack.push(character);
}
else if(character == '(') //check for left parenthesis
{
stack.push(character);
}
else if (character == ')')
{
while(!stack.peek().equals('(') && !stack.isEmpty()){ //add characters until left parenthesis
postFix += stack.pop();
}//end while
if(!stack.isEmpty() && stack.peek().equals('(')){
stack.pop(); // pop/remove left parenthesis
}
}
else
{
postFix += character;
}//end if
}//end for
while(!stack.empty()) //add the remaining elements of stack to postfix expression
{
if(stack.peek().equals('('))
{
postFix = "There is no matching right parenthesis.";
return postFix;
}
postFix += stack.pop();
}
return postFix;
}//end convertToPo
}
The fix is to add a line here (see code comment):
if(character == '*' || character == '-' || character == '/' || character == '+')
{
postFix += ' '; // <-- add space here
while(!stack.empty() && precedence(stack.peek(), character)){
postFix += stack.pop();
}//end while
stack.push(character);
}
after applying the fix the output on my machine looks like:
The Postfix Expression is: 24 4/ 15 3/ / 10 * 4 - 2+