Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Design and implement a class calledPostfixCalculator. Use the algorithm given on

ID: 3596133 • Letter: D

Question

Design and implement a class calledPostfixCalculator. Use the algorithm given on page 374(data abstraction and problem solving with java 3rd edition) to evaluate postfix expressions, as entered into the calculator. Use only the operators +, -, *, %, and /. Assume that the postfix expressions have single digit numbersin the expression and are syntactically correct. This means that the expressions will have already been converted into correct postfix form.The PostfixCalculator should notconvert from infix to postfix form.In order to test the PostfixCalculator, it will be necessary to manuallyconvert your test expressions into postfix form before entering them into the PostfixCalculator. in java only please

Explanation / Answer

Below is your code

PostfixCalculator.java

import java.util.Scanner;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class PostfixCalculator {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

String postfix = scan.nextLine();

scan.close();

postfix = calculate(postfix);

System.out.println(postfix);

}

public static String calculate(String postfix) {

String result = postfix;

String initialPostfix;

do {

initialPostfix = result;

do {

postfix = result;

result = processPostfix(result, '/');

} while (result != postfix);

do {

postfix = result;

result = processPostfix(result, '*');

} while (result != postfix);

do {

postfix = result;

result = processPostfix(result, '+');

} while (result != postfix);

do {

postfix = result;

result = processPostfix(result, '-');

} while (result != postfix);

} while (initialPostfix != result);

return result;

}

private static String processPostfix(String postfix, char operator) {

String numberMatch = "(\-?\d+(?:\.\d+)?)";

Matcher matcher = Pattern.compile(numberMatch + " " + numberMatch + " \" + operator).matcher(postfix);

boolean findMatch = matcher.find();

while (findMatch) {

String match = matcher.group(0);

double firstValue = Double.parseDouble(matcher.group(1));

double secondValue = Double.parseDouble(matcher.group(2));

double resultValue;

switch (operator) {

case '/':

resultValue = firstValue / secondValue;

break;

case '*':

resultValue = firstValue * secondValue;

break;

case '+':

resultValue = firstValue + secondValue;

break;

case '-':

resultValue = firstValue - secondValue;

break;

default:

return postfix;

}

String result = String.valueOf(resultValue);

postfix = postfix.replace(match, result);

findMatch = matcher.find();

}

return postfix;

}

}

Output

6 5 2 3 + 8 * + 3 + *
288.0

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote