Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

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 is from left to right, one character at a time.

While the 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 variable to contain the postfix expression (i.e., the output from this conversion).

Scan the arithmetic expression from left to right.

While there are more symbols in the arithmetic expression,

{

After a symbol is scanned, there are four (4) basic rules to observe and apply accordingly:

If the symbol is an operand (i.e., 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 either of the parentheses onto the output string. Discard them.

}

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 than the one that was currently read, pop that operator from off the stack, and write it to the output string. This process 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

Push the recently scanned symbol onto the stack.

}

4. When 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 that will store operands only.

Scan the postfix string one token (i.e., numbers) at a time.

While there are more tokens 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 t2 operator 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 {

Only the following are considered valid nestings:

( )

{ }

[ ]

{ ( ) }

[ ( ) ]

[ { } ]

[ { ( ) } ]

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.

Here's what I was given from my teacher

-1 Arithmetic class

-Another arithmetic class defining the "isBalance" method.

-Test class

.I just need to fill in some methods, but I do need to turn it in with this format. Please help.

import java.util. Stack; import java.util.EmptyStackException; import java.util.Scanner; class Arithmetic { Stack stk; String expression, postfix; int length; Arithmetic(String s) { expression = s; postfix =""; length = expression.length(); stk = new Stack(); } // Validate the expression - make sure parentheses are balanced boolean isBalance() { // Already defined } // Convert expression to postfix notation void postfixExpression() { stk.clear(); // Re-using the stack object Scanner scan = new Scanner(expression); char current; // The algorithm for doing the conversion.... Follow the bullets while (scan.hasNext()) { String token = scan.next(); if (isNumber(token)) // Bullet # 1 postfix = postfix + token + " "; else { current = token.charAt(0); if (isParentheses(current)) // Bullet # 2 begins { if(stk.empty() || current == Constants.LEFT_NORMAL) { // push this element on the stack; } else if (current == Constants.RIGHT_NORMAL) { try { /* Some details ... whatever is popped from the * stack is an object, hence you must cast this * object to its proper type, then extract its * primitive data (type) value. */ Character ch = (Character)stk.pop(); char top = ch.charValue(); while (top != Constants.LEFT_NORMAL) { /* Append token popped onto the output string * Place at least one blank space between * each token */ } } catch(EmptyStackException e) { } } }// Bullet # 2 ends else if (isOperator(current))// Bullet # 3 begins { if(stk.empty()) stk.push(new Character(current)); else { try { // Remember the method peek simply looks at the top // element on the stack, but does not remove it. char top = (Character)stk.peek(); boolean higher = hasHigherPrecedence(top, current); while(top != Constants.LEFT_NORMAL && higher) { postfix = postfix + stk.pop() + " "; top = (Character)stk.peek(); } stk.push(new Character(current)); } catch(EmptyStackException e) { stk.push(new Character(current)); } } }// Bullet # 3 ends } } // Outer loop ends try { while(!stk.empty()) // Bullet # 4 ; // complete this } catch(EmptyStackException e) { } } boolean isNumber(String str) { //define this method } boolean isParentheses(char current) { // define this method; } boolean isOperator(char ch) { // define this method } boolean hasHigherPrecedence(char top, char current) { // define this method } String getPostfix() { // define method } }
import java.util.EmptyStackException; import java.util.Stack; public class Arithmetic { private Stack stk; private int length; String expression; public Arithmetic(String expression) { stk = new Stack(); this.expression = expression; this.length = expression.length(); } // Determine if parentheses are balanced boolean isBalance() { int index = 0; boolean fail = false; try { while (index < length && !fail) { char ch = expression.charAt(index); switch (ch) { case Constants.LEFT_NORMAL: stk.push(new Character(ch)); break; case Constants.RIGHT_NORMAL: stk.pop(); break; default: break; }//end of swtich index++; }//end of while }//end of try catch (EmptyStackException e) { System.out.println(e.toString()); fail = true; } if (stk.empty() && !fail) return true; else return false; } } 
class RPN { public static void main(String[] arg) { String s[] = {"5 + ) * ( 2", " 2 + ( - 3 * 5 ) ", "(( 2 + 3 ) * 5 ) * 8 ", "5 * 10 + ( 15 - 20 ) ) - 25", " 5 + ( 5 * 10 + ( 15 - 20 ) - 25 ) * 9" }; for (int i = 0; i < s.length; i++) { Arithmetic a = new Arithmetic(s[i]); if (a.isBalance()) { System.out.println("Expression " + s[i] + " is balanced "); a.postfixExpression(); System.out.println("The post fixed expression is " + a.getPostfix()); a.evaluateRPN(); // Supply the necessary codes to determine the validity of your answers } else System.out.println("Expression is not balanced "); } } }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Inductive Databases And Constraint Based Data Mining

Authors: Saso Dzeroski ,Bart Goethals ,Pance Panov

2010th Edition

1489982175, 978-1489982179

More Books

Students also viewed these Databases questions

Question

2. Outline the business case for a diverse workforce.

Answered: 1 week ago