Question

This project is designed to practice with OOP, stack data structure, its applications, and C++/Java programming language. YouYour program must be able to work with int operands and it must recognize binary operators +, -, *,/,%, and ^. In addition, i

0 0
Add a comment Improve this question Transcribed image text
Answer #1

package DS;

import java.util.*;

import java.util.Stack;

  

// Defines a class InfixToPostfixEvaluate

public class InfixToPostfixEvaluate

{

// Method to evaluate expression

public int evaluateExpression(String stringExpression)

{

// Creates a Stack of type integer

Stack<Integer> numbers = new Stack<>();

// Creates a Stack for operators

Stack<Character> operations = new Stack<>();

  

// Loops till end of the expression

for(int counter = 0; counter <

stringExpression.length(); counter++)

{

// Extracts the current character

char currentCharacter =

stringExpression.charAt(counter);

  

// Check if the current character is a number

if(Character.isDigit(currentCharacter))

{

// To stores the number form of the character

int num = 0;

  

// Loops for greater than one digit number

while (Character.isDigit(currentCharacter))

{

// Converts current character to integer

// by subtracting '0' from it

num = num * 10 + (currentCharacter - '0');

  

// Increase the counter by one

counter++;

  

// Checks if counter value is less than

// expression length

if(counter < stringExpression.length())

// Extracts the character at

// counter index position

currentCharacter =

stringExpression.charAt(counter);

// Otherwise come out of the loop

else

break;

}// End of while loop

  

// Decrease the counter by one

counter--;

  

// Push the number to stack

numbers.push(num);

}// End of if condition

  

// Otherwise checks if the current character is

// Opening parenthesis

else if(currentCharacter == '(')

{

// Push the character to stack

operations.push(currentCharacter);

}// End of else if condition   

  

// Otherwise checks if the current character is

// closing parenthesis

else if(currentCharacter == ')')

{

// Extracts data from stack till

// opening parenthesis

while(operations.peek()!='(')

{

// Calls the method to perform

// calculation

int result = performOperation(numbers,

operations);

// Push the current result to stack

numbers.push(result);

}// End of while loop

  

// Pops out the stack top element

operations.pop();

}// End of else if condition

  

// Otherwise checks if the current character is

// operator

else if(checkForOperator(currentCharacter))

{

// Loops till stack is not empty

// Checks the precedence of operators

// in the stack till highest precedence

while(!operations.isEmpty() &&

operatorPrecedence(currentCharacter)

< operatorPrecedence(

operations.peek()))

{

// Calls the method to perform

// calculation

int result = performOperation(numbers,

operations);

// Pushes the current result to stack

numbers.push(result);

}// End of while loop

  

// Pushes the current operator to stack

operations.push(currentCharacter);

}// End of else if condition

}// End of for loop

  

// Loops till stack is not empty

// for rest of the expression

while(!operations.isEmpty())

{

// Calls the method to perform

// calculation

int result = performOperation(numbers,

operations);

// Pushes the current result to stack

numbers.push(result);

}// End of while loop

// Returns the result by pop out the

// top element from stack

return numbers.pop();

}// End of method

// Method to return operator precedence

static int operatorPrecedence(char currentOperator)

{

// Checks the current operator

// and returns the operator precedence

switch (currentOperator)

{

case '+':

case '-':

return 1;

case '*':

case '/':

return 2;

case '^':

return 3;

}// End of switch case

// -1 for invalid character

return -1;

}// End of method

// Method to perform operation based on the operator

public int performOperation(Stack<Integer> numbers,

Stack<Character> operations)

{

// Extracts top two elements from the stack

int second = numbers.pop();

int first = numbers.pop();

  

// Extracts operator from stack

char currentOperator = operations.pop();

  

// Checks the operator

switch (currentOperator)

{

case '+':

return second + first;

case '-':

return first - second;

case '*':

return second * first;

case '/':

if (second == 0)

throw new

UnsupportedOperationException

("Cannot divide by zero");

return first / second;

}// End of switch case

return 0;

}// End of method

// Method to check the parameter character

// returns true is the character is operator

// otherwise returns false

public boolean checkForOperator(char currentCharacter)

{

return (currentCharacter == '+' ||

currentCharacter == '-' ||

currentCharacter == '/' ||

currentCharacter == '*' ||

currentCharacter == '^');

}// End of method

// main method definition

public static void main(String[] pms)

{

// Scanner class object created

Scanner sc = new Scanner(System.in);

// Accepts an expression

System.out.print("Enter an expression: ");

String infixExpression = sc.nextLine();

  

InfixToPostfixEvaluate ipe = new

InfixToPostfixEvaluate();

  

// Calls the method to evaluate and display the result

System.out.println("\n Result: " +

ipe.evaluateExpression(infixExpression));

}// End of main method

}// End of class

Sample Output:

Enter an expression: 17 / (2 + 3) - 13

Result: -10

Add a comment
Know the answer?
Add Answer to:
This project is designed to practice with OOP, stack data structure, its applications, and C++/Java programming...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a java program for the following: Your program reads an infix expression represented by a...

    Write a java program for the following: Your program reads an infix expression represented by a string S from the standard input (the keyboard). Then your program converts the infix expression into a postfix expression P using the algorithm. Next, your program evaluates the postfix expression P to produce a single result R. At last, your program displays the original infix expression S, the corresponding postfix expression P and the final result R on the standard output ( the screen...

  • Objective To acquire expertise in stack manipulation and management, subroutine linkage and retur...

    Objective To acquire expertise in stack manipulation and management, subroutine linkage and return conventions, and recursive procedures. Description You are to create a MIPS programming assignment that returns postfix representation of the input and create an expression tree. Your MIPS program should make use of the expression tree to store the input and provide, by means of an adequate traversal, the value for the expression. Your solution should be structured according to the following steps: Step 1: Convert expression from...

  • JAVA, please You must write a robust program meaning that your program should not crash with...

    JAVA, please You must write a robust program meaning that your program should not crash with any given data. Data validation must be done any time that user enters an input. Write a program that 1. Gets an infix expression form the user and evaluate the expression using stack ADT a. Finds the postfix equivalent of the given infix expression b. Evaluate the created postfix expression. c. Note: your program should not crash when you enter an invalid expression such...

  • tack Assignment Objective: to be familiar with stack operations and applications Requirements: (a) Implement a Java...

    tack Assignment Objective: to be familiar with stack operations and applications Requirements: (a) Implement a Java program that take in an infix expression from the user and output the expression in postfix notation. (b) [15 points bonusl If all the operands in the input are numeric, then your program should evaluate the expression and display its value Hints: deta algorithm for converting an infix expression to the equivalent postf x listed at CSIS ace.edu/n wolf/CS122/infix ostfix.htm

  • In c++ Section 1. Stack ADT – Overview  Data Items The data items in a stack...

    In c++ Section 1. Stack ADT – Overview  Data Items The data items in a stack are of generic DataType. This means use should use templating and your Node class. Structure  The stack data items are linearly ordered from the most recently added (the top) to the least recently added (the bottom). This is a LIFO scheme. Data items are inserted onto (pushed) and removed from (popped) the top of the stack.  Operations  Constructor. Creates an empty stack.  Copy constructor....

  • For this project you will implement a simple calculator. Your calculator is going to parse infix...

    For this project you will implement a simple calculator. Your calculator is going to parse infix algebraic expressions, create the corresponding postfix expressions and then evaluate the postfix expressions. The operators it recognizes are: +, -, * and /. The operands are integers. Your program will either evaluate individual expressions or read from an input file that contains a sequence of infix expressions (one expression per line). When reading from an input file, the output will consist of two files:...

  • C++: Learning Outcomes Implement two stacks and use them to implement an infix to prefix expression...

    C++: Learning Outcomes Implement two stacks and use them to implement an infix to prefix expression convertor Stacks A stack is an abstract data type which uses a sequential container and limits access to that container to one end. You may enter or remove from the container, but only at one end. Using the Linked List data structure from your last homework assignment, implement a Stack of type string. The Stack should only have one data member: the Linked List....

  • (In Java) you will be creating a GUI for your calculator that evaluates the postfix expression. I...

    (In Java) you will be creating a GUI for your calculator that evaluates the postfix expression. I have already created the postfix class that converts the expression from infix to postfix. Here's the postFix class and its stack class (https://paste.ofcode.org/bkwPyCMEBASXQL4pR2ym43) ---> PostFix class (https://paste.ofcode.org/WsEHHugXB38aziWRrp829n)--------> Stack class Your calculator should have: Text field for the postfix expression Text field for the result Two buttons: Evaluate and Clear You can start with the code written below and improvise to work with this...

  • You are to write a program name expressionTree.java that evaluates an infix expression entered by the...

    You are to write a program name expressionTree.java that evaluates an infix expression entered by the user. The expression may contain the following tokens: (1) Integer constants (a series of decimal digits). (2)   One alphabetic character - "x" (representing a value to be supplied later). (3)   Binary operators (+, -, *, / and % (modulo)). (4)   Parentheses          You will parse the input expression creating an expression tree with the tokens, then use the postOrder tree traversal algorithm to extract...

  • Programming Assignment 2 – RPN Calculator – Infix to Postfix Conversion and The Evaluations of the Postfix Expression. You are to design and implement and algorithm in Java, to input an Infix expressi...

    Programming Assignment 2 – RPN Calculator – Infix to Postfix Conversion and The Evaluations of the Postfix Expression. You are to design and implement and algorithm in Java, to input an Infix expression , convert to a postfix expression and finally evaluate the postfix expression… Follow the examples done during class lectures… We are used to infix notation - ”3 + 4” - where the operator is between the operands. There is also prefix notation, where the operand comes before...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT