Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Help! Stacks, Infix To Postfix, Evaluating, Checking Validation of Expressions! Hello! I need help with writing protions of the code and altering it so the

Help! Stacks, Infix To Postfix, Evaluating, Checking Validation of Expressions!

Hello! I need help with writing protions of the code and altering it so the operands are actual numbers and not variables such as, a, b, c. Please edit and write out the missing methods. Thanks! Below I have posted the requirements and method descriptions and the code I have written partially. I have already created an arraystack class.

image text in transcribed

image text in transcribed

image text in transcribed

image text in transcribed

image text in transcribed

image text in transcribed

image text in transcribed

import java.util.Scanner;

public class InfixExpression {

private String str;

public InfixExpression(String str) {

this.str = str;

clean();

// if (!isValid()) {

// throw new IllegalArgumentException();

// }

}

@Override

public String toString() {

return str;

}

private boolean isBalanced() {

StackInterface openDelimiterStack = new ArrayStack();

int characterCount = str.length();

boolean isBalanced = true;

int index = 0;

char nextCharacter = ' ';

while (isBalanced && (index

nextCharacter = str.charAt(index);

switch (nextCharacter) {

case '(':

case '[':

case '{':

openDelimiterStack.push(nextCharacter);

break;

case ')':

case ']':

case '}':

if (openDelimiterStack.isEmpty())

isBalanced = false;

else {

char openDelimiter = openDelimiterStack.pop();

isBalanced = isPaired(openDelimiter, nextCharacter);

}

break;

default:

break;

}

index++;

}

if (!openDelimiterStack.isEmpty()) {

isBalanced = false;

}

return isBalanced;

}

private boolean isPaired(char open, char close) {

return ((open == '(' && close == ')') || (open == '[' && close == ']') || (open == '{' && close == '}'));

}

private boolean isValid() {

for (int i = 0; i

if (!isValidCharacter(str.charAt(i))) {

return false;

}

}

if (!isBalanced()) {

return false;

}

if (!isValidInfixExpression()) {

return false;

}

return true;

}

private boolean isValidInfixExpression() {

for (int i = 0; i

if (!isValidCharacter(str.charAt(i))) {

return false;

}

}

ArrayStack checkStack = new ArrayStack();

if ((str.length() == 1) && (isCharNumber(str.charAt(0)))) {

return true;

}

for (int i = 0; i

if (checkStack.isEmpty()) {

if (isCharNumber(str.charAt(i)) || isCharBracket(str.charAt(i))) {

checkStack.push(str.charAt(i));

} else {

return false;

}

} else {

if (isCharNumber(str.charAt(i)) && !isCharNumber(checkStack.peek())) {

} else if (isCharOperator(str.charAt(i))) {

if (isCharNumber(checkStack.peek()) || isCharBracket(checkStack.peek())) {

checkStack.push(str.charAt(i));

} else {

return false;

}

}

}

}

return false;

}

private boolean isCharNumber(char c) {

for (int i = 0; i

if (c == '0' || c == '1' || c == '2' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8'

|| c == '9') {

return true;

}

}

return false;

}

private boolean isCharOperator(char c) {

for (int i = 0; i

if (c == '(' || c == ')' || c == '+' || c == '-' || c == '/' || c == '*' || c == '^' || c == '%' || c == '['

|| c == ']' || c == '{' || c == '}' || c == ' ') {

return true;

}

}

return false;

}

private boolean isCharBracket(char c) {

for (int i = 0; i

if (c == '(' || c == ')' || c == '[' || c == ']' || c == '{' || c == '}' || c == ' ') {

return true;

}

}

return false;

}

private boolean isValidCharacter(char c) {

if (isCharNumber(c) || isCharOperator(c)) {

return true;

}

return false;

}

private void clean() {

String newStr = "";

if (str.contains(" ")) {

str.replace(" ", "");

}

for (int i = 0; i

if (isCharNumber(str.charAt(i + 1)) && isCharNumber(str.charAt(i))) {

newStr = newStr;

}

newStr = newStr + str.charAt(i) + " ";

}

newStr = newStr.substring(0, newStr.length() - 1) + str.charAt(str.length() - 1);

/ewStr = newStr + str.charAt(str.length()-1);

str = newStr;

}

public String getPostfixExperssion() {

StackInterface operatorStack = new ArrayStack();

String postFix = "";

int index = 0;

char nextCharacter;

char topOperator;

for (int i = 0; i

if (str.charAt(i) != ' ') {

nextCharacter = str.charAt(index);

} else {

nextCharacter = ' ';

}

index++;

switch (nextCharacter) {

case '0':

case '1':

case '2':

case '3':

case '4':

case '5':

case '6':

case '7':

case '8':

case '9':

postFix = postFix + nextCharacter;

break;

case '^':

operatorStack.push(nextCharacter);

break;

case '+':

case '-':

case '*':

case '/':

while ((!operatorStack.isEmpty())

&& (precedenceOf(nextCharacter)

postFix = postFix + operatorStack.pop();

}

operatorStack.push(nextCharacter);

break;

case '(':

operatorStack.push(nextCharacter);

break;

case ')':

topOperator = operatorStack.pop();

while (topOperator != '(') {

postFix = postFix + topOperator;

topOperator = operatorStack.pop();

}

break;

default:

break;

}

}

while (!operatorStack.isEmpty()) {

topOperator = operatorStack.pop();

postFix = postFix + topOperator;

}

return postFix;

}

// Attributed to

// https://stackoverflow.com/questions/2742198/java-operator-precedence-comparison

private int precedenceOf(char nextCharacter) {

switch (nextCharacter) {

case '+':

case '-':

return 0;

case '*':

case '/':

return 1;

case '^':

return 2;

default:

throw new IllegalArgumentException("Operator unknown: " + nextCharacter);

}

}

// Attributed to

// https://codereview.stackexchange.com/questions/35750/postfix-evaluation-using-a-stack

public int evaluate() {

{

Scanner sc = new Scanner(str);

ArrayStack stack = new ArrayStack();

while (sc.hasNext()) {

if (sc.hasNextInt()) {

stack.push(sc.nextInt());

continue;

}

int b = stack.pop();

int a = stack.pop();

char op = sc.next().charAt(0);

if (op == '+')

stack.push(a + b);

else if (op == '-')

stack.push(a - b);

else if (op == '*')

stack.push(a * b);

else if (op == '/')

stack.push(a / b);

else if (op == '%')

stack.push(a % b);

}

sc.close();

return stack.pop();

}

}

}

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

public class Tester {

public static void main(String[] args) {

// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

StackInterface stack = new ArrayStack();

stack.push(1);

stack.push(5);

stack.push(3);

System.out.println("-----------Testing ArrayStack-----------");

System.out.println("Pushing 1, 5, 3, and peeking for a 3:");

System.out.println(stack.peek()); // Gives 3

stack.pop();

System.out.println("Poping 3, and peeking for a 5:");

System.out.println(stack.peek()); // Gives 5

System.out.println("Checking to see if empty:");

System.out.println(stack.isEmpty()); // Gives false

stack.clear();

System.out.println("Clearing stack and seeing if empty:");

System.out.println(stack.isEmpty()); // Gives true

// System.out.println(stack.peek()); Gives an EmptyStackException

// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

System.out.println("");

System.out.println("-----------Testing InfixExpression-----------");

InfixExpression one = new InfixExpression("4+7*6-10");

System.out.println("Declaring new valid expression. Expecting to see cleaned up expression: 4 + 7 * 6 - 10");

System.out.println(one);

System.out.println("Converting to postfix expression. Expecting to see: 4 7 6 * + 10 -");

System.out.println(one.getPostfixExperssion());

}

}

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

import java.util.Arrays;

import java.util.EmptyStackException;

public class ArrayStack implements StackInterface {

private T[] stack;

private int topIndex;

private int DEFAULT_CAPACITY = 10;

public ArrayStack() {

@SuppressWarnings("unchecked")

T[] tempStack = (T[]) new Object[DEFAULT_CAPACITY];

stack = tempStack;

topIndex = -1;

}

@Override

public void push(T newEntry) {

ensureCapacity();

stack[topIndex + 1] = newEntry;

topIndex++;

}

@Override

public T pop() {

if (isEmpty()) {

throwEmptyStackException();

}

T top = stack[topIndex];

stack[topIndex] = null;

topIndex--;

return top;

}

@Override

public T peek() {

if (isEmpty()) {

throwEmptyStackException();

}

return stack[topIndex];

}

@Override

public boolean isEmpty() {

return topIndex

}

@Override

public void clear() {

while (!isEmpty()) {

pop();

}

topIndex = 0;

}

private void throwEmptyStackException() {

if (isEmpty()) {

throw new EmptyStackException();

}

}

private void ensureCapacity() {

if (topIndex == stack.length - 1) {

int newLength = 2 * stack.length;

stack = Arrays.copyOf(stack, newLength);

}

}

}

Naming requirements (not following any of these may result in a score of 0) You will have exactly four source code files: Stacklnterface.java (an interface you are provided) ArrayStack.java (your array-based implementation of Stacklnterface), InfixExpression.java, and Tester.java You will use the default package (this means there should be no package statements in any of your files). Preliminaries: Review the algorithms in chapter 5 for: Determining whether parentheses in an algebraic expression are balanced correctly Converting an infix expression to a postfix expression Evaluating a postfix expression Read chapter 6 to understand how to implement a stack using an array Overall goal: Naming requirements (not following any of these may result in a score of 0) You will have exactly four source code files: Stacklnterface.java (an interface you are provided) ArrayStack.java (your array-based implementation of Stacklnterface), InfixExpression.java, and Tester.java You will use the default package (this means there should be no package statements in any of your files). Preliminaries: Review the algorithms in chapter 5 for: Determining whether parentheses in an algebraic expression are balanced correctly Converting an infix expression to a postfix expression Evaluating a postfix expression Read chapter 6 to understand how to implement a stack using an array Overall goal

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_2

Step: 3

blur-text-image_3

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

Pro PowerShell For Database Developers

Authors: Bryan P Cafferky

1st Edition

1484205413, 9781484205419

More Books

Students also viewed these Databases questions

Question

What is the purpose of the Salary Structure Table?

Answered: 1 week ago

Question

What is the scope and use of a Job Family Table?

Answered: 1 week ago