Question: Here's the problem that I have to solve: Write a Java program that uses a Stack data structure to evaluate postfix expressions. Your program takes

Here's the problem that I have to solve:

Write a Java program that uses a Stack data structure to evaluate postfix expressions. Your program takes a postfix expression as an input,for example:3 42.3+ 5.25* ,from the user and calculates/display the result of the expression.

What I'm having trouble is getting it to reading and calculating it as postfix

Here's my code:

import java.util.Scanner; public class Assignment2 { public static void main(String[] args) {

Scanner scan = new Scanner(System.in); myStack stack = new myStack(); System.out.println("Please enter a postfix expression: "); String input = scan.nextLine(); String[] values = input.split(" "); for(String terms : values) { if(terms.equals("+") || terms.equals("-") || terms.equals("*") || terms.equals("/") || terms.equals("^") ) { Double var2 = stack.pop(); Double var1 = stack.pop(); switch(terms) { case "+": stack.push(var1 + var2); break; case "-": stack.push(var1 - var2); break; case "*": stack.push(var1 * var2); break; case "/": stack.push(var1 / var2); break; // case "^": stack.push(var1 * var1); default: break; } } } double value = Double.parseDouble(values[2]); System.out.println(); } }

A separate class called MyStack:

import java.util.Stack; public class MyStack implements StackInterface {

Stack mystack; public MyStack() { mystack = new Stack<>(); } @Override public void push(T newEntry) { mystack.push(newEntry); } @Override public T peek() { return mystack.peek(); } @Override public T pop() { return mystack.pop(); } @Override public boolean isEmpty() { return mystack.isEmpty(); } @Override public void clear() { mystack.clear(); } }

Stack Interface class: public interface StackInterface { //@param public void push(T newEntry); //@return public T pop(); //@return public T peek(); //@return public boolean isEmpty(); public void clear(); }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!