This discussion is archived
4 Replies Latest reply: May 14, 2010 6:26 PM by 843798 RSS

Postfix mathematical expression calculator program not running

843798 Newbie
Currently Being Moderated
The following are my classes and when I try to run the program it asks for input and if I enter anything other than "q" without the quotes, it just hangs (no crashing but doesn't return anything either).

Here is my Main class:
package assignment_5_1;
import java.util.Scanner;
public class Main
{
    public static void main(String[] args)
    {
        PostfixExpression postfixExpression;
        Scanner kbScan = new Scanner(System.in);
        
        while (true)
        {
            System.out.println("Enter a postfix expression or q to quit: ");
            String expression = kbScan.nextLine();
            System.out.println(expression);
            expression.trim();
            System.out.println(expression);
            if (expression.equalsIgnoreCase("q"))
            {
                break;
            } // out of loop
            postfixExpression = new PostfixExpression(expression);
            System.out.println(expression + " => " + postfixExpression);
        }
        System.out.println("Bye");
    }
}
Here is my PostfixExpression class:
/* Delimiters:
 * ==> \d <==       A digit: [0-9]
==> \D <==     A non-digit: [^0-9]
 http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html */

package assignment_5_1;

import java.util.Scanner;
import java.util.Stack;

public class PostfixExpression
    {
    private String postfixExpression;
    private String value = null; // null or "" ?
    private Stack <String> stack;
    
    Scanner kb = new Scanner(System.in);
    
    public PostfixExpression(String postfixExpression)
    {
        this.postfixExpression = postfixExpression;
        value = evaluate();
    }
    public String getExpression()
    {
        return postfixExpression;
    }

    private String evaluate()
    {
        String input = kb.next(), result = ""; // isn't input the same as postfixExpression?
        stack = new Stack<String>();
        while(kb.hasNext())
        {
            if(isOperand(input))
            {
                stack.push(input);
            }
            else if(isOperator(input))
            {
                if(stack.isEmpty())
                {
                    return "Missing both LHS and RHS operands.";
                }
                
                String operand2 = stack.pop();

                if(stack.isEmpty())
                {
                    return "Missing LHS operand.";
                }

                String operand1 = stack.pop();

                String operator = input;

                String s1 = "Hi";
                
                s1 = "Hello";

                input = null; // Does this free up ram eventually?
                result = compute(operand1, operator, operand2);
                stack.push(result);
            }
            else
            {
                return "Invalid token";
            }
            if(stack.size() != 1)
            {
                return "Invalid postfix expression.";
            }
            else
            {
                result = stack.pop();
            }  
        }
        return result;
    }
    
    private static boolean isOperand(String token)
    {
        try
        {
            int operand = Integer.parseInt(token);
            return true;
        }
        catch(NumberFormatException e)
        {
            return false;
        }
    }
    private static boolean isOperator(String token)
    {
        if(token.equals("+") || token.equals("-") || token.equals("/") || token.equals("*") || token.equals("%"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    private static String compute(String operand1, String operator, String operand2)
    {
        int x = Integer.parseInt(operand1);
        int y = Integer.parseInt(operand2);
        int z;

//        if(y == 0 && (operator.equals("/") || operator.equals("%")))
//        {
//            return "An attempt to divide by 0";
//        }
        
        try
        {
            if(operator.equals("+"))
            {
                z = x + y;
            }
            else if(operator.equals("-"))
            {
                z = x - y;
            }
            else if(operator.equals("*"))
            {
                z = x * y;
            }
            else if(operator.equals("/"))
            {
                z = x/y;
            }
            else if(operator.equals("%"))
            {
                z = x%y;
            }
            else
            {
                return "Invalid operator";
            }
            String result = Integer.toString(z);
            return result;
        }
        catch(NumberFormatException e)
        {
            return "An attempt was made to divide by 0.";
        }
    }
    public String toString()
    {
        return value;
    }
}
Here is the output I currently get:
Enter a postfix expression or q to quit: 
1 2 +
1 2 +
1 2 +
Here is my desired output:
Enter a postfix expression or q to quit:
1 2 +
1 2 + => 3
Enter a postfix expression or q to quit:
1 2 + 3 *
1 2 + 3 * => 9
Enter a postfix expression or q to quit:
1 2 3 + 9
1 2 3 + 9 => Invalid postfix expresion - try again
Enter a postfix expression or q to quit:
1 2 3 + *
1 2 3 + * => 5
Enter a postfix expression or q to quit:
1 2 3 * * 5 +
1 2 3 * * 5 + => 11
Enter a postfix expression or q to quit:
1 2 + 3 -
1 2 + 3 - => 0
Enter a postfix expression or q to quit:
1 2 + 3 4 * + 6 * 9 /
1 2 + 3 4 * + 6 * 9 / => 10
Enter a postfix expression or q to quit:
1 2 3
1 2 3 => Invalid postfix expresion - try again
Enter a postfix expression or q to quit:
1 + 2
1 + 2 => Missing LHS operand - try again
Enter a postfix expression or q to quit:
+ 1 2
+ 1 2 => Missing both LHS and RHS operands - try again
Enter a postfix expression or q to quit:
1 0 /
1 0 / => Attempt to divide by 0 - try again
Enter a postfix expression or q to quit:
2 0 %
2 0 % => Attempt to divide by 0 - try again
Enter a postfix expression or q to quit:
1 2+
1 2+ => invalid operator - try again
Enter a postfix expression or q to quit:
q
bye
I would REALLY appreciate it if someone could help me with this!
Thanks in advance!
  • 1. Re: Postfix mathematical expression calculator program not running
    Kayaman Guru
    Currently Being Moderated
    Well, in your PostfixExpression class' method evaluate() you right in the beginning read another line of input from the user (for no reason too, since you already got the input earlier).

    That's why it's hanging. It's expecting the user to input something. Remove the keyboard read and use the data that was passed into the constructor instead.

    Also this is posted in the totally wrong forum. How is your question related to the Monitoring/Management/Debugging/Profiling APIs?

    Edited by: Kayaman on 9.5.2010 10:54
  • 2. Re: Postfix mathematical expression calculator program not running
    843798 Newbie
    Currently Being Moderated
    Oops, I posted in this forum because I had seen the word "Debugging" and incorrectly assumed that I should post here. Also, I assigned postfixExpression to the variable input as opposed to re-obtaining it from the keyboard but now it just always gives me an output that says that my postfix expression is invalid even though it isn't. Could you please check why the bug still exists?

    Here is my slightly revised PostfixExpression class:
    /* Delimiters:
     * ==> \d <==       A digit: [0-9]
    ==> \D <==     A non-digit: [^0-9]
     http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html */
    
    package assignment_5_1;
    
    import java.util.Scanner;
    import java.util.Stack;
    
    public class PostfixExpression
    {
        private String postfixExpression;
        private String value = null; // null or "" ?
        private Stack <String> stack;
        
        //Scanner kb = new Scanner(System.in);
        
        public PostfixExpression(String postfixExpression)
        {
            this.postfixExpression = postfixExpression;
            value = evaluate();
        }
        public String getExpression()
        {
            return postfixExpression;
        }
    
        private String evaluate()
        {
            //kb.next() // isn't input the same as postfixExpression?
            String input = postfixExpression, result = "";
            
            stack = new Stack<String>();
    //        while(true)
    //        {
                if(isOperand(input))
                {
                    stack.push(input);
                }
                else if(isOperator(input))
                {
                    if(stack.isEmpty())
                    {
                        return "Missing both LHS and RHS operands.";
                    }
                    
                    String operand2 = stack.pop();
    
                    if(stack.isEmpty())
                    {
                        return "Missing LHS operand.";
                    }
    
                    String operand1 = stack.pop();
    
                    String operator = input;
    
    //                String s1 = "Hi";
    //                
    //                s1 = "Hello";
    
                    input = null; // Does this free up ram eventually?
                    result = compute(operand1, operator, operand2);
                    stack.push(result);
                }
                else
                {
                    return "Invalid token";
                }
                if(stack.size() != 1)
                {
                    return "Invalid postfix expression.";
                }
                else
                {
                    result = stack.pop();
                }  
                return result;
    //        }
            
        }
        
        private static boolean isOperand(String token)
        {
            try
            {
                int operand = Integer.parseInt(token);
                return true;
            }
            catch(NumberFormatException e)
            {
                return false;
            }
        }
        private static boolean isOperator(String token)
        {
            if(token.equals("+") || token.equals("-") || token.equals("/") || token.equals("*") || token.equals("%"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        private static String compute(String operand1, String operator, String operand2)
        {
            int x = Integer.parseInt(operand1);
            int y = Integer.parseInt(operand2);
            int z;
    
    //        if(y == 0 && (operator.equals("/") || operator.equals("%")))
    //        {
    //            return "An attempt to divide by 0";
    //        }
            
            try
            {
                if(operator.equals("+"))
                {
                    z = x + y;
                }
                else if(operator.equals("-"))
                {
                    z = x - y;
                }
                else if(operator.equals("*"))
                {
                    z = x * y;
                }
                else if(operator.equals("/"))
                {
                    z = x/y;
                }
                else if(operator.equals("%"))
                {
                    z = x%y;
                }
                else
                {
                    return "Invalid operator";
                }
                String result = Integer.toString(z);
                return result;
            }
            catch(NumberFormatException e)
            {
                return "An attempt was made to divide by 0.";
            }
        }
        public String toString()
        {
            return value;
        }
    }
  • 3. Re: Postfix mathematical expression calculator program not running
    Kayaman Guru
    Currently Being Moderated
    Well, now you push the whole expression on the stack instead of dividing it into parts first. You need to split the String by whitespace first and push them all on the stack before processing.
  • 4. Re: Postfix mathematical expression calculator program not running
    843798 Newbie
    Currently Being Moderated
    EDIT: I FIXED MY MISTAKE. I JUST PUT THE WRONG EXCEPTION IN THE CATCH BLOCK.

    Ok so now I get an error when attempting to divide by 0 even though I have try-catch blocks.

    Here is my PostfixExpression class now:
    // Purpose: To evaluate postfix expressions
    
    package assignment_5_1;
    
    import java.util.Scanner;
    import java.util.Stack;
    
    public class PostfixExpression
    {
        private String postfixExpression;
        private String value = null; // null or "" ?
        private Stack <String> stack;
        
        //Scanner kb = new Scanner(System.in);
        
        public PostfixExpression(String postfixExpression)
        {
            this.postfixExpression = postfixExpression;
            value = evaluate();
        }
        public String getExpression()
        {
            return postfixExpression;
        }
    
        private String evaluate()
        {
            //kb.next() // isn't input the same as postfixExpression?
            //String input = postfixExpression,
            String result = "", token = "";
            Scanner expressionScan = new Scanner(postfixExpression);
            stack = new Stack<String>();
    
           while(expressionScan.hasNext())
            {
    
                    token = expressionScan.next();
                    if(isOperand(token))
                    {
                        stack.push(token);
                    }
                    else if(isOperator(token))
                    {
                        if(stack.isEmpty())
                        {
                            return "Missing both LHS and RHS operands. - try again.";
                        }
    
                        String operand2 = stack.pop();
    
                        if(stack.isEmpty())
                        {
                            return "Missing LHS operand - try again.";
                        }
    
                        String operand1 = stack.pop();
    
                        String operator = token;
    
        //                String s1 = "Hi";
        //
        //                s1 = "Hello";
    
                        token = null; // Does this free up ram eventually?
                        result = compute(operand1, operator, operand2);
                        stack.push(result);
                    }
                    else
                    {
                        return "Invalid token";
                    }
           }
    
    
                if(stack.size() != 1)
                {
                    return "Invalid postfix expression. - try again";
                }
                else
                {
                    result = stack.pop();
                }  
                return result;
    //        }
            
        }
        
        private static boolean isOperand(String token)
        {
            try
            {
                int operand = Integer.parseInt(token);
                return true;
            }
            catch(NumberFormatException e)
            {
                return false;
            }
        }
        private static boolean isOperator(String token)
        {
            if(token.equals("+") || token.equals("-") || token.equals("/") || token.equals("*") || token.equals("%"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        private static String compute(String operand1, String operator, String operand2)
        {
            int x = Integer.parseInt(operand1);
            int y = Integer.parseInt(operand2);
            int z;
    
    //        if(y == 0 && (operator.equals("/") || operator.equals("%")))
    //        {
    //            return "An attempt to divide by 0";
    //        }
            
            try
            {
                if(operator.equals("+"))
                {
                    z = x + y;
                }
                else if(operator.equals("-"))
                {
                    z = x - y;
                }
                else if(operator.equals("*"))
                {
                    z = x * y;
                }
                else if(operator.equals("/"))
                {
                    z = x/y;
                }
                else if(operator.equals("%"))
                {
                    z = x%y;
                }
                else
                {
                    return "Invalid operator";
                }
                String result = Integer.toString(z);
                return result;
            }
            catch(NumberFormatException e)
            {
                return "An attempt was made to divide by 0.";
            }
        }
        public String toString()
        {
            return value;
        }
    }
    EDIT: I FIXED MY MISTAKE. I JUST PUT THE WRONG EXCEPTION IN THE CATCH BLOCK.