SlideShare a Scribd company logo
The concept of stack is extremely important in computer science and is used in a wide variety of
problems. This assignment requires you to write a program that can be used to evaluate ordinary
arithmetic expressions that contains any of the five arithmetic operators (+, -, *, /, %).
This exercise requires three distinct steps, namely:-
Verify that the infix arithmetic expression (the original expression), that may contain regular
parentheses, is properly formed as far as parentheses are concerned.
If the parenthesized expression is properly formed, convert the expression from an infix
expression to its equivalent postfix expression, called Reverse Polish Notation (RPN) named
after the Polish Mathematician J. Lukasiewics.
Evaluate the postfix expression, and print the result.
Step 1 - Verify that the expression
Given an arithmetic expression, called an infixed expression, to verify that it is properly formed
as far as parentheses are concerned, do the following:
Create an empty stack to hold left parenthesis ONLY.
Scanned the arithmetic expression from left to right, one character at a time.
While there are more characters in the arithmetic expression
{
If the character is a left parenthesis ‘(‘, push it on to the stack. However if the character is a right
parenthesis, ‘)’, visit the stack and pop the top element from off the stack.
}
If the stack contains any element at the end of reading the arithmetic expression, then the
expression was not properly formed.
Step 2 - Convert infixed expression to postfix
Given that an arithmetic expression is properly form with respect to parentheses, do the
following:
Create an empty stack to hold any arithmetic operators and left parenthesis, ONLY.
A string to contain the postfix expression – the output from this conversion.
Scan the arithmetic expression from left to right.
While the are more symbols in the arithmetic expression,
{
After a symbol is scanned, there are four (4) basic rules to observed and apply accordingly:
If the symbol is an operand (a number), write it to the output string.
If the symbol is an operator and if the stack is empty, push the symbol on the stack.
Otherwise, if the symbol is either ‘(‘ or ‘)’, check for the following conditions:
If the symbol is ‘(‘, push on to the stack,
Otherwise
If the symbol is ‘)’
{
Pop everything from the operator stack down to the first ‘(‘. Write each item
popped from the stack to the output string. Do not write the item ‘)’. Discard it.
}
If the symbol scanned is an arithmetic operator, check for the following and apply accordingly:
If the operator on the top of the stack has higher or equal precedence, that operator is popped
from off the stack, and is written to the to the output string. This process is continues until one of
two things happen:
Either the first ‘(‘ is encountered. When this occurs, the ‘(‘ is removed from the stack and is
discarded, and the recently scanned symbol is placed on the stack
OR
The operator on the stack has lower precedence than the one just scanned. When this situation
arises, the recently scanned symbol is pushed onto the stack.
}
4. After the arithmetic expression is exhausted, any operator is remaining on the stack must be
popped from off and is written to the output string.
Step 3 - Evaluate the post fixed expression
Initialize an empty stack.
While there are more symbols in the postfix string
{
If the token is an operand, push it onto the stack.
If the token is an operator
{
Pop the two topmost values from the stack, and store them in the order t1, the topmost, and t2 the
second value.
Calculate the partial result in the following order t2operator t1
Push the result of this calculation onto the stack.
NOTE: If the stack does not have two operands, a malformed postfix expression has occurred,
and evaluation should be terminated.
}
}
When the end of the input string is encountered, the result of the expression is popped from the
stack.
NOTE: If the stack is empty or if it has more than one operand remaining, the result is unreliable.
Extend this algorithm to include square brackets and curly braces. For example, expressions of
the following kind should be considered:
2 + { 2 * ( 10 – 4 ) / [ { 4 * 2 / ( 3 + 4) } + 2 ] – 9 }
2 + } 2 * ( 10 – 4 ) / [ { 4 * 2 / ( 3 + 4) } + 2 ] – 9 {
NOTE: The following patterns form valid parenthesizations:
( )
{ }
[ ]
[ ( ) ]
{ ( ) }
[ { ( ) } ]
All other forms are invalid.
Implement the above two algorithms for the following binary operators: addition +, subtraction -,
multiplication *, division /, and modulus operation %. All operations are integer operations. To
keep things simple, place at least one blank space between each token in the input string.
Solution
Driver.java
import java.io.IOException;
import java.io.DataInputStream;
public class Driver {
public static void main(String[] args) {
// TODO Test the stack
ArithmeticExpressionConversions entry = new ArithmeticExpressionConversions();
String in = getData("Please enter a mathematical operation. -1 to quit: ");
/*
* Loop until the user enters -1 to exit the program
*/
while (in.compareTo("-1") != 0 ) {
if (entry.processEntry(in)) {
/*
* The string entered is cleaned up, spaces removed, etc.
*/
System.out.print("Entry processed: ");
entry.printInput();
/*
* Entry is converted to Postfixed notation and displayed
*/
System.out.println("Entry converted to postfix: " + entry.convertInfixToPostfix());
System.out.print("Entry converted to: ");
entry.printPostString();
/*
* The Postfixed entry is evaluated and the answer displayed
*/
int answer = entry.evaluatePostfixExpression();
System.out.println("The answer is " + String.valueOf(answer));
}
in = getData("Enter another mathematical operation. -1 to quit: ");
}
}
/*
* This method is a generic method to retrieve user input as a string
*/
public static String getData(String prompt) {
System.out.print(prompt);
String data = "";
DataInputStream mykb = new DataInputStream(System.in);
try {
data = mykb.readLine();
} catch (IOException e) {
System.out.println("Entry not valid.");
}
return data;
}
}
ArithmeticExpressionConversions.java
public class ArithmeticExpressionConversions {
/**
* input stores the re-formatted user input, stored as a string to handle any character
*/
private String[] input;
/**
* Creates a stack used to convert infixed notation to postfixed
*/
private Stack postStack;
/**
* Holds postfixed entries
*/
private String[] postString;
/**
* Default Constructor
*/
public ArithmeticExpressionConversions() {
this(50);
}
/**
* Full Constructor
* @param input
* @param postStack
* @param postString
*
*/
public ArithmeticExpressionConversions(int s) {
input = new String[s];
postStack = new Stack(s);
postString = new String[s];
}
/**
* Converts an infixed string array to a postfixed string array
* @return
*/
public boolean convertInfixToPostfix() {
int i = 0;
int j = 0;
while (input[i] != null) {
if (input[i].compareTo("+") == 0
|| input[i].compareTo("-") == 0
|| input[i].compareTo("*") == 0
|| input[i].compareTo("/") == 0
|| input[i].compareTo("(") == 0) {
postStack.push(input[i]);
} else if (input[i].compareTo(")") == 0) {
boolean repeat = true;
String comp = (String) postStack.peek();
while (comp.compareTo("(") != 0) {
postString[j] = (String) postStack.pop();
comp = (String) postStack.peek();
j++;
}
postStack.pop();
} else {
postString[j] = input[i];
j++;
}
i++;
}
String holder;
while (postStack.getTop() != -1) {
holder = (String) postStack.pop();
if (holder.compareTo("(") != 0) {
postString[j] = holder;
j++;
}
}
return true;
}
public int getValue(String s) {
if (s.compareTo("+") == 0) { return 1; }
if (s.compareTo("-") == 0) { return 1; }
if (s.compareTo("/") == 0) { return 2; }
if (s.compareTo("*") == 0) { return 2; }
else { return 3; }
}
/**
* Calculates the value of a postfixed string array
* @return
*/
public int evaluatePostfixExpression() {
int value1;
int value2;
Stack evalStack = new Stack(50);
int i = 0;
while (postString[i] != null) {
if (postString[i].compareTo("+") == 0) {
value1 = Integer.parseInt(evalStack.pop().toString());
value2 = Integer.parseInt(evalStack.pop().toString());
evalStack.push(value2 + value1);
} else if (postString[i].compareTo("-") == 0) {
value1 = Integer.parseInt(evalStack.pop().toString());
value2 = Integer.parseInt(evalStack.pop().toString());
evalStack.push(value2 - value1);
} else if (postString[i].compareTo("*") == 0) {
value1 = Integer.parseInt(evalStack.pop().toString());
value2 = Integer.parseInt(evalStack.pop().toString());
evalStack.push(value2 * value1);
} else if (postString[i].compareTo("/") == 0) {
value1 = Integer.parseInt(evalStack.pop().toString());
value2 = Integer.parseInt(evalStack.pop().toString());
evalStack.push(value2 / value1);
} else {
evalStack.push(postString[i]);
}
i++;
}
return Integer.parseInt((evalStack.pop()).toString());
}
/**
* Takes user input and either formats it or informs user of first found error
* @param n
* @return
*/
public boolean processEntry(String n) {
String[] test = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "+", "-
", "*", "/", "(", ")"};
int balance = 0;
int index = 0;
boolean intFlag = false;
for (int i = 0; i < n.length(); i++) {
for (int j = 0; j <= test.length; j++) {
if (j > 10) {
intFlag = false;
}
if (n.substring(i, i + 1).compareTo(" ") == 0) {
break;
}
if (j >= 17) {
System.out.print("Entry validity check: False - improper character: '");
System.out.println(n.charAt(i) + "'");
return false;
}
if (n.substring(i, i + 1).compareTo(test[j]) == 0) {
if (j == 15) {
balance++;
}
if (j == 16) {
balance--;
}
if (intFlag) {
input[index - 1] = input[index - 1] + test[j];
} else {
input[index] = test[j];
index++;
if (j < 11) {intFlag = true;}
}
break;
}
}
}
if (balance == 0) {
System.out.println("Entry validity check: True");
return true;
} else {
System.out.println("Entry validity check: False - Parenthesis unbalanced");
return false;
}
}
/**
* Provides a method to compare strings to one another
* @param targetKey
* @return
*/
public int compareTo(Object targetKey) {
String tKey = (String) targetKey;
return (this.compareTo(tKey));
}
/**
* Displays what the user entered but reformatted
*/
public void printInput() {
for (int i = 0; i < input.length; i++) {
if (input[i] != null) {
System.out.print(input[i]);
}
}
System.out.println();
}
public boolean matchTest(String s) {
String[] test = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"};
for(int i = 0;i < test.length;i++) {
if(s.compareTo(test[i]) == 0) {
return true;
}
}
return false;
}
/**
* Displays postfixed string array
*/
public void printPostString() {
int i = 0;
while (postString[i] != null) {
System.out.print(postString[i] + " ");
i++;
}
System.out.println();
}
/**
* Sets a value in the entry array
* @param n
* @param i
*/
public void setEntry(String n, int i) {
input[i] = n;
}
/**
* Retrieves an entry in the entry array
* @param i
* @return
*/
public String getEntry(int i) {
return input[i];
}
}
Stack.java
public class Stack {
private Object[] nodes;
private int top;
private int size;
/**
* Default Constructor
*
*/
public Stack() {
this(50);
}
/**
* Full Constructor
* @param s
*/
public Stack(int s) {
top = -1;
size = s;
nodes = new Object[s];
}
/**
* Push puts an object on the top of the stack as long as there is room
* in the stack.
* @param newObject
* @return
*/
public boolean push(Object newObject) {
if(top == size - 1)
return false;
else {
top = top + 1;
nodes[top] = newObject;
return true;
}
}
/**
* Pop returns and removes the object on top of the stack as long as there
* are items in the stack.
* @return
*/
public Object pop() {
int topLoc;
if(top == -1)
return null;
else {
topLoc = top;
top = top - 1;
return nodes[topLoc];
}
}
/**
* Peek returns the top item in the stack without deleting it as long
* as there are items in the stack.
* @return
*/
public Object peek() {
int topLoc;
if(top == -1)
return null;
else {
return nodes[top];
}
}
/**
* showAll will show the entire contents of the stack without modification.
*/
public void showAll() {
for(int i = top; i >= 0; i--) {
}
}
/**
* getTop returns the value of the top of the stack.
* @return
*/
public int getTop() {return top;}
/**
* getSize returns the size of the stack.
* @return
*/
public int getSize() {return size;}
}

More Related Content

PDF
Applications of stack
PDF
2. Stack. Write a program that uses the stack class (you can use.pdf
PPT
data structure and algorithm by bomboat_3
PPTX
Unit 2 application of stack
PPT
MO 2020 DS Stacks 3 AB.ppt
PPT
Computer notes - Postfix
PDF
Applications of Stack
PPT
computer notes - Data Structures - 7
Applications of stack
2. Stack. Write a program that uses the stack class (you can use.pdf
data structure and algorithm by bomboat_3
Unit 2 application of stack
MO 2020 DS Stacks 3 AB.ppt
Computer notes - Postfix
Applications of Stack
computer notes - Data Structures - 7

Similar to The concept of stack is extremely important in computer science and .pdf (20)

PPTX
week9-prefixinfixandpostfixnotations-191013065821.pptx
PPTX
Arithmetic expression INFIX TO POSTFIX CONVERTION saraswathi ramalingam
PPTX
Prefix, Infix and Post-fix Notations
PPTX
infixtopostfixconversion-110304220159-phpapp01.pptx
PDF
Data structuresUsing java language and develop a prot.pdf
PPTX
Data structures (Infix, Prefix and Postfix notations).pptx
PPTX
Evaluation of prefix expression with example
PDF
Assume an infix expression can only contain five operators, + .pdf
PDF
Infix to Prefix (Conversion, Evaluation, Code)
PPTX
Topic 2_revised.pptx
PPT
Arithmetic notation conversion infix to1
PPT
Unit IV-infix to postfix and eval.ppt dsa
PPT
Application of Stacks
PPTX
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
PDF
Description of a JAVA programYou are to write a program name Infi.pdf
PDF
java write a program to evaluate the postfix expressionthe program.pdf
PPTX
Stack_Application_Infix_Prefix.pptx
PPTX
conversion of Infix to Postfix conversion using stack
PPTX
Infix postfixcoversion
PDF
C applications
week9-prefixinfixandpostfixnotations-191013065821.pptx
Arithmetic expression INFIX TO POSTFIX CONVERTION saraswathi ramalingam
Prefix, Infix and Post-fix Notations
infixtopostfixconversion-110304220159-phpapp01.pptx
Data structuresUsing java language and develop a prot.pdf
Data structures (Infix, Prefix and Postfix notations).pptx
Evaluation of prefix expression with example
Assume an infix expression can only contain five operators, + .pdf
Infix to Prefix (Conversion, Evaluation, Code)
Topic 2_revised.pptx
Arithmetic notation conversion infix to1
Unit IV-infix to postfix and eval.ppt dsa
Application of Stacks
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
Description of a JAVA programYou are to write a program name Infi.pdf
java write a program to evaluate the postfix expressionthe program.pdf
Stack_Application_Infix_Prefix.pptx
conversion of Infix to Postfix conversion using stack
Infix postfixcoversion
C applications
Ad

More from arihantsherwani (20)

PDF
The age of the Earth is estimated from the amount of uranium isotope .pdf
PDF
Suppose Michael creates an RSA cryptosystem with a very large mod­ulu.pdf
PDF
Match the terms to the definitions provided.Question 2 optionsd.pdf
PDF
Simple linear regression and multiple regression are both based on t.pdf
PDF
Sand, Mell, and Rand are partners who share incomes and losses in a .pdf
PDF
PLEASE ANSWER ALL THE QUESTIONES BELOW AS DETAILED AS POSSIBLE. THAN.pdf
PDF
Livingstone is a marble freak and loves to paly at school. During th.pdf
PDF
Invertebrates colonized terrestrial environments independently of ve.pdf
PDF
Is there a similarity transformation that maps Delta ABC to Delta DBF.pdf
PDF
Felix and Janet Green live in Swarthmore, PA. Janets father, Larry,.pdf
PDF
Do the leaves of all plants have an abscission layer If not, what h.pdf
PDF
Discuss the outcomes and challenges surrounding shortages in various.pdf
PDF
Create a C program that implements The Game of Life cellular auto.pdf
PDF
Copy a String in Reverse Order Write a program with a loop and ind.pdf
PDF
Compare and contrast prokaryotic cells and eukaryotic cells. Compare.pdf
PDF
Case Study 1Hotel worker Danny Ruiz was living with his wife and f.pdf
PDF
Assignment Submission Assignment, you submit answers by question by .pdf
PDF
A linear dynamical system can be created for two masses connected by.pdf
PDF
A 7 year old female with a history of previous UTI’s suddenly develo.pdf
PDF
5. Toxco, Inc. emits a noxious gaseous substance as a waste product o.pdf
The age of the Earth is estimated from the amount of uranium isotope .pdf
Suppose Michael creates an RSA cryptosystem with a very large mod­ulu.pdf
Match the terms to the definitions provided.Question 2 optionsd.pdf
Simple linear regression and multiple regression are both based on t.pdf
Sand, Mell, and Rand are partners who share incomes and losses in a .pdf
PLEASE ANSWER ALL THE QUESTIONES BELOW AS DETAILED AS POSSIBLE. THAN.pdf
Livingstone is a marble freak and loves to paly at school. During th.pdf
Invertebrates colonized terrestrial environments independently of ve.pdf
Is there a similarity transformation that maps Delta ABC to Delta DBF.pdf
Felix and Janet Green live in Swarthmore, PA. Janets father, Larry,.pdf
Do the leaves of all plants have an abscission layer If not, what h.pdf
Discuss the outcomes and challenges surrounding shortages in various.pdf
Create a C program that implements The Game of Life cellular auto.pdf
Copy a String in Reverse Order Write a program with a loop and ind.pdf
Compare and contrast prokaryotic cells and eukaryotic cells. Compare.pdf
Case Study 1Hotel worker Danny Ruiz was living with his wife and f.pdf
Assignment Submission Assignment, you submit answers by question by .pdf
A linear dynamical system can be created for two masses connected by.pdf
A 7 year old female with a history of previous UTI’s suddenly develo.pdf
5. Toxco, Inc. emits a noxious gaseous substance as a waste product o.pdf
Ad

Recently uploaded (20)

PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
Pharma ospi slides which help in ospi learning
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Lesson notes of climatology university.
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Basic Mud Logging Guide for educational purpose
PDF
Computing-Curriculum for Schools in Ghana
PDF
Complications of Minimal Access Surgery at WLH
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Cell Types and Its function , kingdom of life
Supply Chain Operations Speaking Notes -ICLT Program
Pharma ospi slides which help in ospi learning
Abdominal Access Techniques with Prof. Dr. R K Mishra
human mycosis Human fungal infections are called human mycosis..pptx
Pharmacology of Heart Failure /Pharmacotherapy of CHF
2.FourierTransform-ShortQuestionswithAnswers.pdf
TR - Agricultural Crops Production NC III.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Lesson notes of climatology university.
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Basic Mud Logging Guide for educational purpose
Computing-Curriculum for Schools in Ghana
Complications of Minimal Access Surgery at WLH
O7-L3 Supply Chain Operations - ICLT Program
Cell Types and Its function , kingdom of life

The concept of stack is extremely important in computer science and .pdf

  • 1. The concept of stack is extremely important in computer science and is used in a wide variety of problems. This assignment requires you to write a program that can be used to evaluate ordinary arithmetic expressions that contains any of the five arithmetic operators (+, -, *, /, %). This exercise requires three distinct steps, namely:- Verify that the infix arithmetic expression (the original expression), that may contain regular parentheses, is properly formed as far as parentheses are concerned. If the parenthesized expression is properly formed, convert the expression from an infix expression to its equivalent postfix expression, called Reverse Polish Notation (RPN) named after the Polish Mathematician J. Lukasiewics. Evaluate the postfix expression, and print the result. Step 1 - Verify that the expression Given an arithmetic expression, called an infixed expression, to verify that it is properly formed as far as parentheses are concerned, do the following: Create an empty stack to hold left parenthesis ONLY. Scanned the arithmetic expression from left to right, one character at a time. While there are more characters in the arithmetic expression { If the character is a left parenthesis ‘(‘, push it on to the stack. However if the character is a right parenthesis, ‘)’, visit the stack and pop the top element from off the stack. } If the stack contains any element at the end of reading the arithmetic expression, then the expression was not properly formed. Step 2 - Convert infixed expression to postfix Given that an arithmetic expression is properly form with respect to parentheses, do the following: Create an empty stack to hold any arithmetic operators and left parenthesis, ONLY. A string to contain the postfix expression – the output from this conversion. Scan the arithmetic expression from left to right. While the are more symbols in the arithmetic expression, { After a symbol is scanned, there are four (4) basic rules to observed and apply accordingly: If the symbol is an operand (a number), write it to the output string. If the symbol is an operator and if the stack is empty, push the symbol on the stack. Otherwise, if the symbol is either ‘(‘ or ‘)’, check for the following conditions: If the symbol is ‘(‘, push on to the stack,
  • 2. Otherwise If the symbol is ‘)’ { Pop everything from the operator stack down to the first ‘(‘. Write each item popped from the stack to the output string. Do not write the item ‘)’. Discard it. } If the symbol scanned is an arithmetic operator, check for the following and apply accordingly: If the operator on the top of the stack has higher or equal precedence, that operator is popped from off the stack, and is written to the to the output string. This process is continues until one of two things happen: Either the first ‘(‘ is encountered. When this occurs, the ‘(‘ is removed from the stack and is discarded, and the recently scanned symbol is placed on the stack OR The operator on the stack has lower precedence than the one just scanned. When this situation arises, the recently scanned symbol is pushed onto the stack. } 4. After the arithmetic expression is exhausted, any operator is remaining on the stack must be popped from off and is written to the output string. Step 3 - Evaluate the post fixed expression Initialize an empty stack. While there are more symbols in the postfix string { If the token is an operand, push it onto the stack. If the token is an operator { Pop the two topmost values from the stack, and store them in the order t1, the topmost, and t2 the second value. Calculate the partial result in the following order t2operator t1 Push the result of this calculation onto the stack. NOTE: If the stack does not have two operands, a malformed postfix expression has occurred, and evaluation should be terminated. } } When the end of the input string is encountered, the result of the expression is popped from the
  • 3. stack. NOTE: If the stack is empty or if it has more than one operand remaining, the result is unreliable. Extend this algorithm to include square brackets and curly braces. For example, expressions of the following kind should be considered: 2 + { 2 * ( 10 – 4 ) / [ { 4 * 2 / ( 3 + 4) } + 2 ] – 9 } 2 + } 2 * ( 10 – 4 ) / [ { 4 * 2 / ( 3 + 4) } + 2 ] – 9 { NOTE: The following patterns form valid parenthesizations: ( ) { } [ ] [ ( ) ] { ( ) } [ { ( ) } ] All other forms are invalid. Implement the above two algorithms for the following binary operators: addition +, subtraction -, multiplication *, division /, and modulus operation %. All operations are integer operations. To keep things simple, place at least one blank space between each token in the input string. Solution Driver.java import java.io.IOException; import java.io.DataInputStream; public class Driver { public static void main(String[] args) { // TODO Test the stack ArithmeticExpressionConversions entry = new ArithmeticExpressionConversions(); String in = getData("Please enter a mathematical operation. -1 to quit: "); /*
  • 4. * Loop until the user enters -1 to exit the program */ while (in.compareTo("-1") != 0 ) { if (entry.processEntry(in)) { /* * The string entered is cleaned up, spaces removed, etc. */ System.out.print("Entry processed: "); entry.printInput(); /* * Entry is converted to Postfixed notation and displayed */ System.out.println("Entry converted to postfix: " + entry.convertInfixToPostfix()); System.out.print("Entry converted to: "); entry.printPostString(); /* * The Postfixed entry is evaluated and the answer displayed */ int answer = entry.evaluatePostfixExpression(); System.out.println("The answer is " + String.valueOf(answer)); } in = getData("Enter another mathematical operation. -1 to quit: "); } } /* * This method is a generic method to retrieve user input as a string
  • 5. */ public static String getData(String prompt) { System.out.print(prompt); String data = ""; DataInputStream mykb = new DataInputStream(System.in); try { data = mykb.readLine(); } catch (IOException e) { System.out.println("Entry not valid."); } return data; } } ArithmeticExpressionConversions.java public class ArithmeticExpressionConversions { /** * input stores the re-formatted user input, stored as a string to handle any character */ private String[] input; /** * Creates a stack used to convert infixed notation to postfixed */ private Stack postStack; /** * Holds postfixed entries */ private String[] postString; /** * Default Constructor */ public ArithmeticExpressionConversions() { this(50); }
  • 6. /** * Full Constructor * @param input * @param postStack * @param postString * */ public ArithmeticExpressionConversions(int s) { input = new String[s]; postStack = new Stack(s); postString = new String[s]; } /** * Converts an infixed string array to a postfixed string array * @return */ public boolean convertInfixToPostfix() { int i = 0; int j = 0; while (input[i] != null) { if (input[i].compareTo("+") == 0 || input[i].compareTo("-") == 0 || input[i].compareTo("*") == 0 || input[i].compareTo("/") == 0 || input[i].compareTo("(") == 0) { postStack.push(input[i]); } else if (input[i].compareTo(")") == 0) { boolean repeat = true; String comp = (String) postStack.peek(); while (comp.compareTo("(") != 0) { postString[j] = (String) postStack.pop(); comp = (String) postStack.peek(); j++; }
  • 7. postStack.pop(); } else { postString[j] = input[i]; j++; } i++; } String holder; while (postStack.getTop() != -1) { holder = (String) postStack.pop(); if (holder.compareTo("(") != 0) { postString[j] = holder; j++; } } return true; } public int getValue(String s) { if (s.compareTo("+") == 0) { return 1; } if (s.compareTo("-") == 0) { return 1; } if (s.compareTo("/") == 0) { return 2; } if (s.compareTo("*") == 0) { return 2; } else { return 3; } } /** * Calculates the value of a postfixed string array * @return */ public int evaluatePostfixExpression() { int value1; int value2; Stack evalStack = new Stack(50); int i = 0; while (postString[i] != null) { if (postString[i].compareTo("+") == 0) { value1 = Integer.parseInt(evalStack.pop().toString());
  • 8. value2 = Integer.parseInt(evalStack.pop().toString()); evalStack.push(value2 + value1); } else if (postString[i].compareTo("-") == 0) { value1 = Integer.parseInt(evalStack.pop().toString()); value2 = Integer.parseInt(evalStack.pop().toString()); evalStack.push(value2 - value1); } else if (postString[i].compareTo("*") == 0) { value1 = Integer.parseInt(evalStack.pop().toString()); value2 = Integer.parseInt(evalStack.pop().toString()); evalStack.push(value2 * value1); } else if (postString[i].compareTo("/") == 0) { value1 = Integer.parseInt(evalStack.pop().toString()); value2 = Integer.parseInt(evalStack.pop().toString()); evalStack.push(value2 / value1); } else { evalStack.push(postString[i]); } i++; } return Integer.parseInt((evalStack.pop()).toString()); } /** * Takes user input and either formats it or informs user of first found error * @param n * @return */ public boolean processEntry(String n) { String[] test = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "+", "- ", "*", "/", "(", ")"}; int balance = 0; int index = 0; boolean intFlag = false; for (int i = 0; i < n.length(); i++) { for (int j = 0; j <= test.length; j++) { if (j > 10) { intFlag = false;
  • 9. } if (n.substring(i, i + 1).compareTo(" ") == 0) { break; } if (j >= 17) { System.out.print("Entry validity check: False - improper character: '"); System.out.println(n.charAt(i) + "'"); return false; } if (n.substring(i, i + 1).compareTo(test[j]) == 0) { if (j == 15) { balance++; } if (j == 16) { balance--; } if (intFlag) { input[index - 1] = input[index - 1] + test[j]; } else { input[index] = test[j]; index++; if (j < 11) {intFlag = true;} } break; } } } if (balance == 0) { System.out.println("Entry validity check: True"); return true; } else { System.out.println("Entry validity check: False - Parenthesis unbalanced"); return false; } } /**
  • 10. * Provides a method to compare strings to one another * @param targetKey * @return */ public int compareTo(Object targetKey) { String tKey = (String) targetKey; return (this.compareTo(tKey)); } /** * Displays what the user entered but reformatted */ public void printInput() { for (int i = 0; i < input.length; i++) { if (input[i] != null) { System.out.print(input[i]); } } System.out.println(); } public boolean matchTest(String s) { String[] test = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}; for(int i = 0;i < test.length;i++) { if(s.compareTo(test[i]) == 0) { return true; } } return false; } /** * Displays postfixed string array */ public void printPostString() { int i = 0;
  • 11. while (postString[i] != null) { System.out.print(postString[i] + " "); i++; } System.out.println(); } /** * Sets a value in the entry array * @param n * @param i */ public void setEntry(String n, int i) { input[i] = n; } /** * Retrieves an entry in the entry array * @param i * @return */ public String getEntry(int i) { return input[i]; } } Stack.java public class Stack { private Object[] nodes; private int top; private int size; /** * Default Constructor * */ public Stack() {
  • 12. this(50); } /** * Full Constructor * @param s */ public Stack(int s) { top = -1; size = s; nodes = new Object[s]; } /** * Push puts an object on the top of the stack as long as there is room * in the stack. * @param newObject * @return */ public boolean push(Object newObject) { if(top == size - 1) return false; else { top = top + 1; nodes[top] = newObject; return true; } } /** * Pop returns and removes the object on top of the stack as long as there * are items in the stack. * @return */
  • 13. public Object pop() { int topLoc; if(top == -1) return null; else { topLoc = top; top = top - 1; return nodes[topLoc]; } } /** * Peek returns the top item in the stack without deleting it as long * as there are items in the stack. * @return */ public Object peek() { int topLoc; if(top == -1) return null; else { return nodes[top]; } } /** * showAll will show the entire contents of the stack without modification. */ public void showAll() { for(int i = top; i >= 0; i--) { } } /** * getTop returns the value of the top of the stack. * @return
  • 14. */ public int getTop() {return top;} /** * getSize returns the size of the stack. * @return */ public int getSize() {return size;} }