Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: Post Fixed Math Expressions using Stack

  1. #1
    Junior Member
    Join Date
    Mar 2013
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Post Fixed Math Expressions using Stack

    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)


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Post Fixed Math Expressions using Stack

    Do you have a question or problem? Please ask it.

    Please edit your post and wrap your code with
    [code=java]
    <YOUR CODE HERE>
    [/code]
    to get highlighting and preserve formatting.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Mar 2013
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Post Fixed Math Expressions using Stack

    Code added above

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Post Fixed Math Expressions using Stack

    how can I get three cases in my switch statement to work?
    What does the code do now? What do you want it to do differently?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Mar 2013
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Post Fixed Math Expressions using Stack

    Currently the only thing that works is default in my switch statement(I can output the top item in the stack) I get an error when using any of the other cases, Exception in thread "main" java.lang.NumberFormatException: For input string: "+"
    at sun.misc.FloatingDecimal.readJavaFormatString(Floa tingDecimal.java:1241)
    at java.lang.Double.parseDouble(Double.java:540)
    at Project2Option1.main(Project2Option1.java:21)

    Process completed.


    I would like to be able to take input which will have spaces (ex: 2 3 -) and perform the post fixed math expr

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Post Fixed Math Expressions using Stack

    java.lang.NumberFormatException: For input string: "+"
    at sun.misc.FloatingDecimal.readJavaFormatString(Floa tingDecimal.java:1241)
    at java.lang.Double.parseDouble(Double.java:540)
    at Project2Option1.main(Project2Option1.java:21)
    The statement on line 21 calls the parseDouble() method with the String: "+" and the method throws the exception.
    Why is the code trying to convert the "+" to a double? It should wait until the after the switch statement has selected out the arithmetic operators and the default case gets control.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Mar 2013
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Post Fixed Math Expressions using Stack

    Quote Originally Posted by Norm View Post
    The statement on line 21 calls the parseDouble() method with the String: "+" and the method throws the exception.
    Why is the code trying to convert the "+" to a double? It should wait until the after the switch statement has selected out the arithmetic operators and the default case gets control.
    I do not want to convert "+" to a double, if the program encounters a + I would like it to add the two previous tokens in the string.

    So essentially in case "+": When the we encounter a "+", add the two previous tokens and push the result upon the stack.

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Post Fixed Math Expressions using Stack

    Look at the code in the program. Where is line 21 with the parseDouble() where the error happens?
    Why is that statement located there? It tries to convert the String to a double BEFORE the switch statement has checked the String to be an arithmetic operator like a "+".
    Remove that statement to keep the error from happening.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Mar 2013
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Post Fixed Math Expressions using Stack

    Quote Originally Posted by Norm View Post
    Look at the code in the program. Where is line 21 with the parseDouble() where the error happens?
    Why is that statement located there? It tries to convert the String to a double BEFORE the switch statement has checked the String to be an arithmetic operator like a "+".
    Remove that statement to keep the error from happening.
    Ok I removed that line. Now the error says the stack is empty, Exception in thread "main" java.util.EmptyStackException

     	while(tokens.hasMoreTokens())
    		{
    			thisToken = tokens.nextToken();
     
    			switch(thisToken)
    			{
    				case "+": // Evaluate the math expression  "+"
    					ds.pop(); ds.pop(); 
    					currentToken = Double.parseDouble(thisToken); 
    					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; */
    			}

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Post Fixed Math Expressions using Stack

    When you get an error you need to copy the full text of the error message and post it here.

    What was input to the program? Add a println() statement immediately after the call to the JOptionPane method that prints out what was entered so we can see what the program is using for data. Also add a println() statement after where thisToken gets its value that prints out the value in thisToken.

    The print outs will help you see what the computer sees when the program executes.

    I'm done for tonight. Back tomorrow.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. [SOLVED] fixed
    By lordthomas1993 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: January 30th, 2013, 07:39 PM
  2. [SOLVED] Help with Math.tan and Math.atan
    By Dr.Code in forum Algorithms & Recursion
    Replies: 6
    Last Post: July 2nd, 2012, 05:54 AM
  3. Stack Practice: Evaluating Expressions Syntax
    By Staticity in forum What's Wrong With My Code?
    Replies: 2
    Last Post: October 4th, 2011, 10:35 PM
  4. Confusion with Math.toDegrees() and Math.toRadians(). Please help.
    By marksquall in forum Java Theory & Questions
    Replies: 3
    Last Post: June 23rd, 2011, 01:28 AM
  5. [SOLVED] evaluating postfix expressions using stack
    By lieles in forum What's Wrong With My Code?
    Replies: 4
    Last Post: March 16th, 2011, 11:48 AM

Tags for this Thread