Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

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

Step: 3

blur-text-image

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

Database Processing

Authors: David M. Kroenke

12th Edition International Edition

1292023422, 978-1292023427

More Books

Students also viewed these Databases questions

Question

Do Exercise 7-13 on the LP of Exercise 7-12.

Answered: 1 week ago