SlideShare a Scribd company logo
java write a program to evaluate the postfix expression
the program should ask users for input and show the postfix epression and then the result.
and to have a try and catch exception since we have an empty stack
Solution
Postfix.java
import java.util.Scanner;
public class Postfix
{
/**
* Reads and evaluates multiple postfix expressions.
*/
public static void main (String[] args)
{
String expression, again;
int result;
try
{
Scanner in = new Scanner(System.in);
do
{
PostfixEvaluator evaluator = new PostfixEvaluator();
System.out.println ("Enter a valid postfix expression: ");
expression = in.nextLine();
result = evaluator.evaluate (expression);
System.out.println();
System.out.println ("That expression equals " + result);
System.out.print ("Evaluate another expression [Y/N]? ");
again = in.nextLine();
System.out.println();
}
while (again.equalsIgnoreCase("y"));
}
catch (Exception IOException)
{
System.out.println("Input exception reported");
}
}
}
PostfixEvaluator.java
//import datastructures.ArrayStack;
import java.util.StringTokenizer;
public class PostfixEvaluator
{
/** constant for addition symbol */
private final char ADD = '+';
/** constant for subtraction symbol */
private final char SUBTRACT = '-';
/** constant for multiplication symbol */
private final char MULTIPLY = '*';
/** constant for division symbol */
private final char DIVIDE = '/';
/** the stack */
private ArrayStack stack;
/**
* Sets up this evaluator by creating a new stack.
*/
public PostfixEvaluator()
{
stack = new ArrayStack();
}
/**
* Evaluates the specified postfix expression. If an operand is
* encountered, it is pushed onto the stack. If an operator is
* encountered, two operands are popped, the operation is
* evaluated, and the result is pushed onto the stack.
* //param expr String representation of a postfix expression
* //return int value of the given expression
*/
public int evaluate (String expr)
{
int op1, op2, result = 0;
String token;
StringTokenizer tokenizer = new StringTokenizer (expr);
while (tokenizer.hasMoreTokens())
{
token = tokenizer.nextToken();
if (isOperator(token))
{
op2 = (stack.pop()).intValue();
op1 = (stack.pop()).intValue();
result = evalSingleOp (token.charAt(0), op1, op2);
stack.push (new Integer(result));
}
else
stack.push (new Integer(Integer.parseInt(token)));
}
return result;
}
/**
* Determines if the specified token is an operator.
* //param token String representing a single token
* //return boolean true if token is operator
*/
private boolean isOperator (String token)
{
return ( token.equals("+") || token.equals("-") ||
token.equals("*") || token.equals("/") );
}
/**
* Performs integer evaluation on a single expression consisting of
* the specified operator and operands.
* //param operation operation to be performed
* //param op1 the first operand
* //param op2 the second operand
* //return int value of the expression
*/
private int evalSingleOp (char operation, int op1, int op2)
{
int result = 0;
switch (operation)
{
case ADD:
result = op1 + op2;
break;
case SUBTRACT:
result = op1 - op2;
break;
case MULTIPLY:
result = op1 * op2;
break;
case DIVIDE:
result = op1 / op2;
}
return result;
}
}
ArrayStack.java
import java.util.Arrays;
public class ArrayStack implements StackADT {
private final static int DEFAULT_CAPACITY = 100;
private int top;
private T[] stack;
/**
* Creates an empty stack using the default capacity.
*/
public ArrayStack() {
this(DEFAULT_CAPACITY);
}
/**
* Creates an empty stack using the specified capacity.
*
* //param initialCapacity the initial size of the array
*/
public ArrayStack(int initialCapacity) {
top = 0;
stack = (T[]) (new Object[initialCapacity]);
}
/**
* Adds the specified element to the top of this stack, expanding the
* capacity of the array if necessary.
*
* //param element generic element to be pushed onto stack
*/
public void push(T element) {
if (size() == stack.length) {
expandCapacity();
}
stack[top] = element;
top++;
}
/**
* Creates a new array to store the contents of this stack with twice the
* capacity of the old one.
*/
private void expandCapacity() {
stack = Arrays.copyOf(stack, stack.length * 2);
}
/**
* Removes the element at the top of this stack and returns a reference to
* it.
*
* //return element removed from top of stack
* //throws EmptyCollectionException if stack is empty
*/
public T pop() throws EmptyCollectionException {
if (isEmpty()) {
throw new EmptyCollectionException("stack");
}
top--;
T result = stack[top];
stack[top] = null;
return result;
}
/**
* Returns a reference to the element at the top of this stack. The element
* is not removed from the stack.
*
* //return element on top of stack
* //throws EmptyCollectionException if stack is empty
*/
public T peek() throws EmptyCollectionException {
if (isEmpty()) {
throw new EmptyCollectionException("stack");
}
return stack[top - 1];
}
/**
* Returns true if this stack is empty and false otherwise.
*
* //return true if this stack is empty
*/
public boolean isEmpty() {
return (top == 0);
}
/**
* Returns the number of elements in this stack.
*
* //return the number of elements in the stack
*/
public int size() {
return top;
}
/**
* Returns a string representation of this stack.
*
* //return a string representation of the stack
*/
public String toString() {
String result = "";
for (int scan = 0; scan < top; scan++) {
result = result + stack[scan] + " ";
}
return result;
}
}
StackADT.java
public interface StackADT
{
/**
* Adds the specified element to the top of this stack.
* //param element element to be pushed onto the stack
*/
public void push(T element);
/**
* Removes and returns the top element from this stack.
* //return the element removed from the stack
*/
public T pop();
/**
* Returns without removing the top element of this stack.
* //return the element on top of the stack
*/
public T peek();
/**
* Returns true if this stack contains no elements.
* //return true if the stack is empty
*/
public boolean isEmpty();
/**
* Returns the number of elements in this stack.
* //return the number of elements in the stack
*/
public int size();
/**
* Returns a string representation of this stack.
* //return a string representation of the stack
*/
public String toString();
}
EmptyCollectionException.java
public class EmptyCollectionException extends RuntimeException{
public EmptyCollectionException(String collection)
{
super("The " + collection + " is empty.");
}
}

More Related Content

DOCX
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
PDF
Data structuresUsing java language and develop a prot.pdf
PDF
StackInterface An interface for the ADT stack. Do not modif.pdf
PDF
The concept of stack is extremely important in computer science and .pdf
PDF
Implement the ADT stack by using an array stack to contain its entri.pdf
DOCX
----------Evaluator-java---------------- package evaluator- import j.docx
DOCX
----------Evaluator-java---------------- package evaluator- import j.docx
PDF
Please read the comment ins codeExpressionTree.java-------------.pdf
New folderjsjfArrayStack.classpackage jsjf;publicsynchronize.docx
Data structuresUsing java language and develop a prot.pdf
StackInterface An interface for the ADT stack. Do not modif.pdf
The concept of stack is extremely important in computer science and .pdf
Implement the ADT stack by using an array stack to contain its entri.pdf
----------Evaluator-java---------------- package evaluator- import j.docx
----------Evaluator-java---------------- package evaluator- import j.docx
Please read the comment ins codeExpressionTree.java-------------.pdf

Similar to java write a program to evaluate the postfix expressionthe program.pdf (20)

PDF
Applications of stack
PDF
Data structure lab manual
PPT
Stack, queue and hashing
PPTX
Ch05_Stacks implementation in data structures.pptx
PPT
DOCX
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
PPTX
conversion of Infix to Postfix conversion using stack
DOCX
Need help with writing the test cases for the following code in java-.docx
PDF
Assume an infix expression can only contain five operators, + .pdf
PPTX
DS UNIT1_STACKS.pptx
PPT
Stack in Data Structure
PPT
7 stacksqueues
PPTX
Evaluation of prefix expression with example
PDF
Please review my code (java)Someone helped me with it but i cannot.pdf
PDF
DOCX
PPTX
Stack_Overview_Implementation_WithVode.pptx
PPT
data structure and algorithm by bomboat_3
PPTX
Lec5-Stack-bukc-28022024-112316am (1) .pptx
PPTX
Application of Stack - Yadraj Meena
Applications of stack
Data structure lab manual
Stack, queue and hashing
Ch05_Stacks implementation in data structures.pptx
META-INFMANIFEST.MFManifest-Version 1.0.classpath.docx
conversion of Infix to Postfix conversion using stack
Need help with writing the test cases for the following code in java-.docx
Assume an infix expression can only contain five operators, + .pdf
DS UNIT1_STACKS.pptx
Stack in Data Structure
7 stacksqueues
Evaluation of prefix expression with example
Please review my code (java)Someone helped me with it but i cannot.pdf
Stack_Overview_Implementation_WithVode.pptx
data structure and algorithm by bomboat_3
Lec5-Stack-bukc-28022024-112316am (1) .pptx
Application of Stack - Yadraj Meena
Ad

More from arjuntelecom26 (20)

PDF
Orchids are a type of flowering plant. How would biologists explain .pdf
PDF
Need the mutiple choice answeredSolution1. A small software up.pdf
PDF
MaT Identify the letter of the choice that best matches the phrase o.pdf
PDF
Intravenous PyelogramReason for exam Fever of unknown originTec.pdf
PDF
if you use the command sudo iptables -L -v you will notice that FORW.pdf
PDF
If the total pressure at point E is increased at a constant temperat.pdf
PDF
How did the Great Awakening inspire ordinary citizens to assert thei.pdf
PDF
Charles Darwin Origin of Species3. Discuss the difficulties with s.pdf
PDF
Explain some of the common elements found in an HTML page.Soluti.pdf
PDF
Dynamics - Vibration - natural frequencies and mode shapes Define pr.pdf
PDF
Determine one (1) advantage to selecting an S corporation status. Pr.pdf
PDF
Delegate The role members of Congress serve in representing the i.pdf
PDF
An earthquake measuring 6.4 on the Richter scale struck Japan in Jul.pdf
PDF
A veterinarian amputated a swollen testicle from a zebra at a zoo an.pdf
PDF
Albinism. Some might wonder why this disorder doesnt phase out.pdf
PDF
A Poisson distribution is such that the probability is the same for .pdf
PDF
A concave mirror forms an image on a screen that is twice as large as.pdf
PDF
65 Fri Search Show Me How Payrell entries The prolL reinnent tor Ga.pdf
PDF
Concisely, how may HDL metabolism and the onset of type-II diabetes b.pdf
PDF
You are a correctional manager in a federal high security facility d.pdf
Orchids are a type of flowering plant. How would biologists explain .pdf
Need the mutiple choice answeredSolution1. A small software up.pdf
MaT Identify the letter of the choice that best matches the phrase o.pdf
Intravenous PyelogramReason for exam Fever of unknown originTec.pdf
if you use the command sudo iptables -L -v you will notice that FORW.pdf
If the total pressure at point E is increased at a constant temperat.pdf
How did the Great Awakening inspire ordinary citizens to assert thei.pdf
Charles Darwin Origin of Species3. Discuss the difficulties with s.pdf
Explain some of the common elements found in an HTML page.Soluti.pdf
Dynamics - Vibration - natural frequencies and mode shapes Define pr.pdf
Determine one (1) advantage to selecting an S corporation status. Pr.pdf
Delegate The role members of Congress serve in representing the i.pdf
An earthquake measuring 6.4 on the Richter scale struck Japan in Jul.pdf
A veterinarian amputated a swollen testicle from a zebra at a zoo an.pdf
Albinism. Some might wonder why this disorder doesnt phase out.pdf
A Poisson distribution is such that the probability is the same for .pdf
A concave mirror forms an image on a screen that is twice as large as.pdf
65 Fri Search Show Me How Payrell entries The prolL reinnent tor Ga.pdf
Concisely, how may HDL metabolism and the onset of type-II diabetes b.pdf
You are a correctional manager in a federal high security facility d.pdf
Ad

Recently uploaded (20)

PPTX
master seminar digital applications in india
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Cell Types and Its function , kingdom of life
PDF
RMMM.pdf make it easy to upload and study
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
Pre independence Education in Inndia.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Sports Quiz easy sports quiz sports quiz
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Complications of Minimal Access Surgery at WLH
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Anesthesia in Laparoscopic Surgery in India
master seminar digital applications in india
Insiders guide to clinical Medicine.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
TR - Agricultural Crops Production NC III.pdf
Cell Types and Its function , kingdom of life
RMMM.pdf make it easy to upload and study
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Cell Structure & Organelles in detailed.
Pre independence Education in Inndia.pdf
VCE English Exam - Section C Student Revision Booklet
Renaissance Architecture: A Journey from Faith to Humanism
Sports Quiz easy sports quiz sports quiz
O5-L3 Freight Transport Ops (International) V1.pdf
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
102 student loan defaulters named and shamed – Is someone you know on the list?
Complications of Minimal Access Surgery at WLH
Microbial disease of the cardiovascular and lymphatic systems
Anesthesia in Laparoscopic Surgery in India

java write a program to evaluate the postfix expressionthe program.pdf

  • 1. java write a program to evaluate the postfix expression the program should ask users for input and show the postfix epression and then the result. and to have a try and catch exception since we have an empty stack Solution Postfix.java import java.util.Scanner; public class Postfix { /** * Reads and evaluates multiple postfix expressions. */ public static void main (String[] args) { String expression, again; int result; try { Scanner in = new Scanner(System.in); do { PostfixEvaluator evaluator = new PostfixEvaluator(); System.out.println ("Enter a valid postfix expression: "); expression = in.nextLine(); result = evaluator.evaluate (expression); System.out.println(); System.out.println ("That expression equals " + result); System.out.print ("Evaluate another expression [Y/N]? "); again = in.nextLine(); System.out.println(); } while (again.equalsIgnoreCase("y")); }
  • 2. catch (Exception IOException) { System.out.println("Input exception reported"); } } } PostfixEvaluator.java //import datastructures.ArrayStack; import java.util.StringTokenizer; public class PostfixEvaluator { /** constant for addition symbol */ private final char ADD = '+'; /** constant for subtraction symbol */ private final char SUBTRACT = '-'; /** constant for multiplication symbol */ private final char MULTIPLY = '*'; /** constant for division symbol */ private final char DIVIDE = '/'; /** the stack */ private ArrayStack stack; /** * Sets up this evaluator by creating a new stack. */ public PostfixEvaluator() { stack = new ArrayStack(); } /** * Evaluates the specified postfix expression. If an operand is * encountered, it is pushed onto the stack. If an operator is * encountered, two operands are popped, the operation is * evaluated, and the result is pushed onto the stack. * //param expr String representation of a postfix expression
  • 3. * //return int value of the given expression */ public int evaluate (String expr) { int op1, op2, result = 0; String token; StringTokenizer tokenizer = new StringTokenizer (expr); while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); if (isOperator(token)) { op2 = (stack.pop()).intValue(); op1 = (stack.pop()).intValue(); result = evalSingleOp (token.charAt(0), op1, op2); stack.push (new Integer(result)); } else stack.push (new Integer(Integer.parseInt(token))); } return result; } /** * Determines if the specified token is an operator. * //param token String representing a single token * //return boolean true if token is operator */ private boolean isOperator (String token) { return ( token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/") ); } /**
  • 4. * Performs integer evaluation on a single expression consisting of * the specified operator and operands. * //param operation operation to be performed * //param op1 the first operand * //param op2 the second operand * //return int value of the expression */ private int evalSingleOp (char operation, int op1, int op2) { int result = 0; switch (operation) { case ADD: result = op1 + op2; break; case SUBTRACT: result = op1 - op2; break; case MULTIPLY: result = op1 * op2; break; case DIVIDE: result = op1 / op2; } return result; } } ArrayStack.java import java.util.Arrays; public class ArrayStack implements StackADT { private final static int DEFAULT_CAPACITY = 100; private int top; private T[] stack; /** * Creates an empty stack using the default capacity. */
  • 5. public ArrayStack() { this(DEFAULT_CAPACITY); } /** * Creates an empty stack using the specified capacity. * * //param initialCapacity the initial size of the array */ public ArrayStack(int initialCapacity) { top = 0; stack = (T[]) (new Object[initialCapacity]); } /** * Adds the specified element to the top of this stack, expanding the * capacity of the array if necessary. * * //param element generic element to be pushed onto stack */ public void push(T element) { if (size() == stack.length) { expandCapacity(); } stack[top] = element; top++; } /** * Creates a new array to store the contents of this stack with twice the * capacity of the old one. */ private void expandCapacity() { stack = Arrays.copyOf(stack, stack.length * 2); } /** * Removes the element at the top of this stack and returns a reference to * it. *
  • 6. * //return element removed from top of stack * //throws EmptyCollectionException if stack is empty */ public T pop() throws EmptyCollectionException { if (isEmpty()) { throw new EmptyCollectionException("stack"); } top--; T result = stack[top]; stack[top] = null; return result; } /** * Returns a reference to the element at the top of this stack. The element * is not removed from the stack. * * //return element on top of stack * //throws EmptyCollectionException if stack is empty */ public T peek() throws EmptyCollectionException { if (isEmpty()) { throw new EmptyCollectionException("stack"); } return stack[top - 1]; } /** * Returns true if this stack is empty and false otherwise. * * //return true if this stack is empty */ public boolean isEmpty() { return (top == 0); } /** * Returns the number of elements in this stack. *
  • 7. * //return the number of elements in the stack */ public int size() { return top; } /** * Returns a string representation of this stack. * * //return a string representation of the stack */ public String toString() { String result = ""; for (int scan = 0; scan < top; scan++) { result = result + stack[scan] + " "; } return result; } } StackADT.java public interface StackADT { /** * Adds the specified element to the top of this stack. * //param element element to be pushed onto the stack */ public void push(T element); /** * Removes and returns the top element from this stack. * //return the element removed from the stack */ public T pop(); /** * Returns without removing the top element of this stack. * //return the element on top of the stack
  • 8. */ public T peek(); /** * Returns true if this stack contains no elements. * //return true if the stack is empty */ public boolean isEmpty(); /** * Returns the number of elements in this stack. * //return the number of elements in the stack */ public int size(); /** * Returns a string representation of this stack. * //return a string representation of the stack */ public String toString(); } EmptyCollectionException.java public class EmptyCollectionException extends RuntimeException{ public EmptyCollectionException(String collection) { super("The " + collection + " is empty."); } }