Hello, I have been working on a silly little project for class for over a week now. The directions are below in bold
You may assume the user will enter a one line properly formatted post fixed math expression, with the tokens (operators and operands) separated by white space. You should use the API Stack class and the StringTokenizer class. Declare your Stack object to be a stack that can only store objects in the class Double.
Below is an outline of the program.
import java.util.*; // needed for the StringTokenizer class
import javax.swing.*;
// Declare a Java API Stack object that can store Double objects (Stack<Double> ds = new Stack<Double>()
// Accept the user’s input of the math String into the variable mathExpression
// Evaluate the math expression // see the code below
StringTokenizer tokens = new StringTokenizer(mathExpression, " ");
while(tokens.hasMoreTokens())
{
thisToken = tokens.nextToken();
//processing for token goes here
}
// Pop the stack and output the returned value
Here is my code, mathExpression being the user input. I used a switch statement to determine if the token is a +, -, or * sign. The default case is if the token is just a number. So basically my goal is to take user input which has spaces ex: 2 4 + (post fixed math which really means 2 + 4), and perform the math to return a result while using a stack.
import java.util.*; import javax.swing.*; public class Project2Option1 { public static void main(String[] args) { String mathExpression, thisToken; Double result, number, currentToken; Stack<Double> ds = new Stack<Double>(); // Declare a Java API Stack object that can store Double objects mathExpression = JOptionPane.showInputDialog("Please enter one properly formatted post fixed math expression"); // Accept the user’s input of the math String into the variable mathExpression StringTokenizer tokens = new StringTokenizer(mathExpression); while(tokens.hasMoreTokens()) { thisToken = tokens.nextToken(); currentToken = Double.parseDouble(thisToken); switch(thisToken) { case "+": // Evaluate the math expression "+" ds.pop(); ds.pop(); result = (currentToken) + (currentToken - 1); ds.push(result); break; case "-": //Evaluate the math expression "-" ds.pop(); ds.pop(); result = (currentToken) - (currentToken - 1); ds.push(result); break; case "*": //Evaluate the math expression "*" ds.pop(); ds.pop(); result = (currentToken) * (currentToken - 1); ds.push(result); break; default: //Converting token to a double; numbers entered by user number = Double.parseDouble(thisToken); ds.push(number); break; } } System.out.println("Here is the answer: " + ds.pop()); // Pop the stack and output the returned value } }
My question is, how can I get three cases in my switch statement to work? (they should should examine the token, If its an math operator, pop the stack twice, do the math, and then push the result)