Write JAVA program, Use of Stacks Assume a Machine has a single register and six
ID: 3683930 • Letter: W
Question
Write JAVA program, Use of Stacks Assume a Machine has a single register and six instructions (Problem 2.3.10 from the LAT text.)
LD A places the operand A in the register
ST A places the contents of the register into the variable A
AD A adds the contents of the variable A to the register
SB A subtracts the contents of the variable A from the register
ML A multiples the contents of the register by the variable A
DV A divides the contents of the register by the variable A
Write a program that accepts a postfix expression containing single letter operands and the operators +, -, *, and / and prints a sequence of instructions to evaluate the expression and leaves the result in the register. Use variables of the form TEMPn as temporary variables. For example, using the postfix expression ABC*+DE-/ should print the following: Note: YOU CANOT USE STACK BUILD IN FUNCTION, define own stack.
LD B
ML C
ST TEMP1
LD A
AD TEMP1
ST TEMP2
LD D
SB E
ST TEMP3
LD TEMP2
DV TEMP3
ST TEMP4
Use the following postfix expressions for input
AB+C-
AB-C+DEF-+$
ABC-/BA-+/
ABCDE-+$*EF*
Explanation / Answer
import java.io.*;
class Stack
{
private int[] a;
private int top,m;
public Stack(int max)
{
m=max;
a=new int[m];
top=-1;
}
public void push(int key)
{
a[++top]=key;
}
public int pop()
{
return(a[top--]);
}
}
class Evaluation{
public int calculate(String s)
{
int n,r=0;
n=s.length();
Stack a=new Stack(n);
for(int i=0;i<n;i++)
{
char ch=s.charAt(i);
if(ch>='0'&&ch<='9')
a.push((int)(ch-'0'));
else
{
int x=a.pop();
int y=a.pop();
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;
}
a.push(r);
}
}
r=a.pop();
return(r);
}
}
class PostfixEvaluation
{
public static void main(String[] args)throws IOException
{
String input;
while(true)
{
System.out.println("Enter the postfix expresion");
input=getString();
if(input.equals(""))
break;
Evaluation e=new Evaluation();
System.out.println("Result:- "+e.calculate(input));
}
}
public static String getString()throws IOException
{
DataInputStream inp=new DataInputStream(System.in);
String s=inp.readLine();
return s;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.