Question

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 as: 2 + 4 * (6 -3 2. Implementation: a. Create an interface called Stack with the following methods. All the actual/formal parameters must be of type Object i. size(): returns the size of the stack ii. isEmpty() returns true/false iii. pop returns the object that is at the top of the stack iv. push(Object o) : pushes the object to the top of the stack v. pee(): looks at the object at the top and returns a copy of the object without popping it b. Create another class that implements the Stack interface. This class must have i. an instance variable of type ArrayList ii. implements all the methods from the stack interface iii. add equals method that compares two stacks iv. add a toString method. v. Add a method copy that returns a copy of the stack. c. Implement the driver class with the following methods i. infixToPostfix(String s): This method receives an infix expression and then creates its postfix and returns it. go to the website http://docs.oracle.com/javase/6/docs/api/java/util/StringTokenizer.html and read about the class called StringTokenizer. You need to use this class to tokenize the expression that you receive. In the expression 2 + 3, the tokens are 2, 3, +. If there are any spaces in the expression they must be ignored. Here is the algorithm to convert infix to postfix:  Initialize the stack with the dummy operator #.  Repeat until no more tokens. • Get the next token.  If the next token is an operand, enqueue the operand to the postfix String. Declare a String called postfix, every time you read an operand concatenate that to the postfix string.  If the next token is a (, push it in the stack.  If the next token is a ), pop and enqueue operators to the postfix string until a ( is on the top of the stack. Pop ( out of the stack.  If the next token is an operator, pop and enqueue operators to the postfix until the top of the stack has a lower precedence. Push the current operator into the stack. • If more tokens go to the beginning, If no more tokens, pop and enqueue operators until the dummy oprerator # is on the top of the stack. Pop # out of the stack. • Return the postfix String.  Note that # and (has a precedence lower than other operators. ii. Write a method called: postFixEvaluater(String post) . Use the following algorithm to evaluate a postfix expression. Repeat until no more tokens Get the next token: 1. If the next token is an operand, push it into the stack. 2. If the next token is an operator pop two operands from the stack, do the operation, and push the result back to the stack. After you are done reading all the tokens and doing the operations, the final result is the only thing on the stack when done. (If there’s more than one thing in the stack, there is an error in the expression.) Here is a sample output: Enter your infix expression: 3+7*6/3-8*2 postFix = 3 7 6 * 3 / + 8 2 * - 3 7 6 * 3 / + 8 2 * - = 1 Do you have another expression: yes Enter your infix expression:(7+9)*(6+3*5/3) postFix = 7 9 + 6 3 5 * 3 / + * 7 9 + 6 3 5 * 3 / + * = 176 Do you have another expression :yes Enter your infix expression:3+8*5-3+25/5 postFix = 3 8 5 * + 3 - 25 5 / + 3 8 5 * + 3 - 25 5 / + = 45 Do you have another expression :yes Enter your infix expression :(7+9)*(6+3*5/3 Invalid expression Do you have another expression :no Good Bye

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

`Hey,

Note: Brother in case of any queries, just comment in box I would be very happy to assist all your queries

Stack.h

#ifndef STACK_H

#define STACK_H

#include <iostream>

template <class T>

class StackNode

{

private:

T value;

StackNode<T> *next;

public:

StackNode(T newItem, StackNode<T> *newNext)

{

value = newItem;

next = newNext;

}

StackNode<T> *getNext()

{

return next;

}

T getData()

{

return value;

}

};

// Stack class

template <class T>

class Stack

{

private:

StackNode<T> *top;

public:

Stack();

// Push

void push(T newItem);

// Peek

T peek();

// Pop

T pop();

// isEmpty

bool isEmpty();

// clear

void clear();

// display stack contents

void display();

};

#endif

Stack.cpp

#include "Stack.h"

// Note: if you get an error about nullptr, try using -std=c++0x commandline switch

// or whatever compiler switch forces C++11 standard compiling (-std=c++0x is for g++).

// Stack class

template <class T>

Stack<T>::Stack()

{

top = nullptr;

}

// Push

template <class T>

void Stack<T>::push(T newItem)

{

StackNode<T> *n = new StackNode<T>(newItem, top);

top = n;

}

// Peek

template <class T>

T Stack<T>::peek()

{

return top->getData();

}

// Pop

template <class T>

T Stack<T>::pop()

{

T data;

StackNode<T> *ptr;

if (top == NULL)

return -1;

ptr = top;

top = top->getNext();

data = ptr->getData();

delete ptr;

return data;

}

// isEmpty

template <class T>

bool Stack<T>::isEmpty()

{

return top == nullptr;

}

// clear

template <class T>

void Stack<T>::clear()

{

//top = nullptr;

StackNode<T> *ptr = top, *prev = NULL;

top = nullptr;

while (ptr != NULL)

{

prev = ptr;

ptr = ptr->getNext();

delete prev;

}

}

// display stack contents

template <class T>

void Stack<T>::display()

{

StackNode<T> *node = top;

while (node != NULL)

{

std::cout << node->getData();

node = node->getNext();

}

}

main.cpp

#include <iostream>

#include <cstdlib>

#include <string>

#include <cstring>

#include <fstream>

#include <cmath>

#define OPERATORS 8

using namespace std;

#include "Stack.cpp"

char precedence[OPERATORS][2] = {{'(', 0}, {'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}, {'%', 2}, {'^', 3}, {')', 4}};

/* get the index of the operator in precedence array */

int getIndex(int data)

{

int i;

for (i = 0; i < OPERATORS; i++)

{

if (data == precedence[i][0])

return i;

}

return -1;

}

string convertToPostfix(string infix)

{

Stack<char> *expr = new Stack<char>();

string postfix = "";

int i;

char data;

int index1, index2;

for (i = 0; i < (int)infix.length(); i++)

{

if (infix[i] == ' ')

continue;

/* given input is operator or not */

if ((tolower(infix[i]) >= 'a' && tolower(infix[i] <= 'z')) || (infix[i] >= '0' && infix[i] <= '9'))

{

postfix += infix[i];

if (infix[i + 1] <= '0' || infix[i + 1] >= '9' )

postfix += ' ';

}

else if (infix[i] == ')')

{

data = expr->pop();

while (data != '(' && data != -1)

{

postfix += data;

postfix += ' ';

data = expr->pop();

}

}

else if (infix[i] == '(')

{

expr->push(infix[i]);

}

else

{

data = expr->pop();

if (data == -1)

{

expr->push(infix[i]);

continue;

}

else if (data == '(')

{

expr->push(data);

expr->push(infix[i]);

continue;

}

index1 = getIndex(data);

index2 = getIndex(infix[i]);

while (precedence[index1][1] >= precedence[index2][1])

{

postfix += data;

postfix += ' ';

data = expr->pop();

if (data == -1)

{

expr->push(infix[i]);

break;

}

else if (data == '(')

{

expr->push(data);

expr->push(infix[i]);

data = -1;

break;

}

index1 = getIndex(data);

}

if (data != -1)

{

expr->push(data);

expr->push(infix[i]);

}

}

}

while (1)

{

if ((data = expr->pop()) == -1)

break;

postfix += data;

postfix += ' ';

}

return postfix;

}

int EvalPostfix(string str)

{

Stack<int> *expr = new Stack<int>();

int i,data = -1, operand1, operand2, result;

for (i = 0; i < str.length(); i++)

{

if (isdigit(str[i]))

{

data = (data == -1) ? 0 : data;

data = (data * 10) + (str[i] - 48);

continue;

}

if (data != -1)

{

expr->push(data);

}

if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/' || str[i] == '^')

{

operand2 = expr->pop();

operand1 = expr->pop();

if (operand1 == -1 || operand2 == -1)

break;

switch (str[i])

{

case '+':

result = operand1 + operand2;

expr->push(result);

break;

case '-':

result = operand1 - operand2;

expr->push(result);

break;

case '*':

result = operand1 * operand2;

expr->push(result);

break;

case '/':

result = operand1 / operand2;

expr->push(result);

break;

case '^':

result = pow(operand1, operand2);

expr->push(result);

break;

}

}

data = -1;

}

if (!expr->isEmpty())

return expr->peek();

else{

cout<<"Invalid expression"<<endl;

exit(1);

}

}

int main()

{

string output, str, another;

do{

cout << "\nEnter your infix expression: ";

getline(cin, str);

output = convertToPostfix(str);

cout << "postfix: " << output << endl;

cout<<output<<" = "<<EvalPostfix(output)<<endl;

cout<<"Do you have another expression: ";

cin>>another;

cin.ignore();

}while(another=="yes");

cout<<"Good Bye"<<endl;

return 0;

}

Kindly revert for any queries

Thanks.

Add a comment
Know the answer?
Add Answer to:
JAVA, please You must write a robust program meaning that your program should not crash with...
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
  • In C programming Language Write a version of the infix-to-postfix conversion algorithm. Write a program that converts an...

    In C programming Language Write a version of the infix-to-postfix conversion algorithm. Write a program that converts an ordinary infix arithmetic expression (assume a valid expression is entered) with single-digit integers For Example: Infix expression (6 + 2) * 5 - 8 / 4 to a postfix expression is  62+5*84/- The program should read the expression into character array infix and use the stack functions implemented in this chapter to help create the postfix expression in character array postfix. The...

  • You will write the following files: mystack.h - contains the class definition for the mystack class....

    You will write the following files: mystack.h - contains the class definition for the mystack class. mystack.cpp - contains the definitions for member functions of the mystack class. inpost.cpp - contains your convert() function. inpost.h - contains the function prototype for convert() so that the main() can call it. Each of the files (with the exception of inpost.h) is described in more detail below. All header files should contain header guards to prevent them from being included multiple times in...

  • i want similar for this code to solve two questions : 1- Write a program to...

    i want similar for this code to solve two questions : 1- Write a program to convert a postfix expression to infix expression 2-Write a program to convert an infix expression to prefix expression each question in separate code ( so will be two codes ) #include <iostream> #include <string> #define SIZE 50 using namespace std; // structure to represent a stack struct Stack {   char s[SIZE];   int top; }; void push(Stack *st, char c) {   st->top++;   st->s[st->top] = c;...

  • Stacks are used by compilers to help in the process of evaluating expressions and generating machine...

    Stacks are used by compilers to help in the process of evaluating expressions and generating machine language code.In this exercise, we investigate how compilers evaluate arithmetic expressions consisting only of constants, operators and parentheses. Humans generally write expressions like 3 + 4and 7 / 9in which the operator (+ or / here) is written between its operands—this is called infix notation. Computers “prefer” postfix notation in which the operator is written to the right of its two operands. The preceding...

  • Code should be written in java Write a program to convert an infix expression to postfix...

    Code should be written in java Write a program to convert an infix expression to postfix expression using stack. Algorithm: a) Create a stack b) For each character t in the input stream If(t is an operand) append t to the output. Else if (t is a right parenthesis) Pop and append to the output until a left parenthesis is popped (but do not append this parenthesis to the output). Else if(t is an operator or left parenthesis) Pop and...

  • Python Issue Postfix notation (also known as Reverse Polish Notation or RPN in short) is a...

    Python Issue Postfix notation (also known as Reverse Polish Notation or RPN in short) is a mathematical notation in which operators follow all of its operands. It is different from infix notation in which operators are placed between its operands. The algorithm to evaluate any postfix expression is based on stack and is pretty simple: Initialize empty stack For every token in the postfix expression (scanned from left to right): If the token is an operand (number), push it on...

  • 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...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

  • Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQ...

    Infix Expression Evaluator For this project, write a C program that will evaluate an infix expression. The algorithm REQUIRED for this program will use two stacks, an operator stack and a value stack. Both stacks MUST be implemented using a linked list. For this program, you are to write functions for the linked list stacks with the following names: int isEmpty (stack); void push (stack, data); data top (stack); void pop (stack); // return TRUE if the stack has no...

  • I NEED SAMPLE PRINT OUT AS WELL AS CODE PLEASE!!!! Objectives: To gain experience with stacks....

    I NEED SAMPLE PRINT OUT AS WELL AS CODE PLEASE!!!! Objectives: To gain experience with stacks. Documentation: Explain the purpose of the program as detail as possible - 8%. Develop a solution for the problem and mention algorithms to be used -12% List data structures to be used in solution. - 5%. Give a description of how to use the program and expected input/output - 5% Explain the purpose of each class you develop in the program. - 5%. Programming:...

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