Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Need the solution to the description below as a small Java program that reads in

ID: 3852456 • Letter: N

Question

Need the solution to the description below as a small Java program that reads in a postfix expression that then splits it into an array of strings. I need a "stack of numbers" class to make a stack to do this evaluation. Further explanation of what I need is below this is a warm up excercise for me to understand my eventual project. I learn from solutions and this will greatly help me.

Evaluating a reverse polish (postfix) expression.

2 * (3 + 4) + 5

this might be parsed into a tree, and then the output in reverse polish notation (postfix notation) might be

2 3 4 + * 5 +

Evaluating this (interpreting this) would be to read it from left to right and when you see a number push it on the stack, and when you see an operator, pop the right operand off the stack into a variable r and then pop the left operand off the stack into a variable l, then using a switch on the operator combine l with r using the operator and push the result back onto the stack.

Explanation / Answer

import java.io.*;

class Stack
{
char a[]=new char[1000000];
int top=-1;
  
void push(char c)
{
a[++top]= c;
}

char pop()
{
return a[top--];
}

boolean isEmpty()
{
return (top==-1) ? true : false;
}

char peek()
{
return a[top];
}

}   


class Postfix
{

static Stack st = new Stack();
  
public static void main(String argv[]) throws IOException
{
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
  
System.out.print(" Enter the expression: ");
String input = br.readLine();

System.out.println("The output is:" + converttoPostfix(input));
  
}
  
private static String converttoPostfix(String infix)
{
char c;
String ans = "";
  
for(int i=0;i<infix.length();++i)
{
c = infix.charAt(i);
//if it's an operand, add it to the string
if (Character.isLetter(c))
ans = ans + c;
else if (c=='(')
{
st.push(c);
}
else if (c==')')
{
while (st.peek() != '(')
{
ans = ans + st.pop();
}
st.pop();
}
else
{
while (!st.isEmpty() && !(st.peek()=='(') && precedence(c) <= precedence(st.peek()))
ans = ans + st.pop();
  
st.push(c);
}
}
while (!st.isEmpty())
ans = ans + st.pop();
return ans;
}
  
  
static int precedence(char alpha)
{
if (alpha == '+' || alpha == '-')
return 1;
if (alpha == '*' || alpha == '/' || alpha == '%')
return 2;
return 0;
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote