Java Expression Trees For this assignment you will write a program using and Exp
ID: 3675154 • Letter: J
Question
Java Expression Trees
For this assignment you will write a program using and Expression Tree that reads postfix expression from the user, one per line, then converts the postfix expression to infix, gets the numeric value of the expression, and terminates when the user enters a blank line.
For each postfix expression, due the following:
1. Build an expression tree supporting +-*/
2. Print out the equivalent infix expression, in heavily parenthesesed form. 3. Print out the numeric value of the expression.
3. Print out the numeric value of the expression.
Make sure your main method is in a class called ETreeDriver. Do not print any prompts or values other than the infix expression and resulting value.
Explanation / Answer
/*Headers*/
import java.io.*;
/*Class decleration*/
class Stack
{
/*Access constructor*/
private int[] h;
private int top,m;
/*Constructor*/
public Stack(int max)
{
m=max;
h=new int[m];
top=-1;
}
/*Function*/
public void push(int key)
{
h[++top]=key;
}
public int pop()
{
return(h[top--]);
}
}
/*VALIDATES THE PROCESS*/
class Evaluation
{
/*calculation*/
public int calculate(String s)
{
/*Integer decleration*/
int n,r=0;
n=s.length();
Stack h=new Stack(n);
/*Loop*/
for(int m=0;m<n;m++)
{
char ch=s.charAt(m);
if(ch>='0'&&ch<='9')
h.push((int)(ch-'0'));
else
{
int x=h.pop();
int y=h.pop();
/*case*/
switch(ch)
{
case '+':r=x+y;
break;
case '-':r=y-x;
break;
case '*':r=x*y;
break;
case '/':r=y/x;
break;
default:r=0;
}
h.push(r);
}
}
r=h.pop();
return(r);
}
}
/*Decleration*/
class PostfixEvaluation
{
/*Main method*/
public static void main(String[] args)throws IOException
{
/*String decleration*/
String input;
/*LOOP*/
while(true)
{
System.out.println("Enter the postfix expresion");
input=getString();
if(input.equals(""))
break;
/*Object creation*/
Evaluation e=new Evaluation();
/*Command prompt*/
System.out.println("Result:- "+e.calculate(input));
}
}
/*String manipulation*/
public static String getString()throws IOException
{
DataInputStream inp=new DataInputStream(System.in);
String s=inp.readLine();
return s;
}
/*function ends*/
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.