I'm trying to evaluate postfix expressions but i cannot get it right. I always get the result value as 0 and in my evaluate method it keeps saying my num1 num2 and result have not been initialized. Any help is appreciated.

package collection;
import java.io.*;


public class Postfix {
  private Stack theStack;

  private String input;

  private String output = "";

  public Postfix(String in) {
    input = in;
    int stackSize = input.length();
    theStack = new Stack(stackSize);
  }

  public String doTrans() 
  {
    for (int j = 0; j < input.length(); j++) 
    {
      char ch = input.charAt(j);
      switch (ch) {
      case '+': 
      case '-':
        gotOper(ch, 1); 
        break; //   (precedence 1)
      case '*': // it's * or /
      case '/':
        gotOper(ch, 2); // go pop operators
        break; //   (precedence 2)
      case '(': // it's a left paren
        theStack.push(ch); // push it
        break;
      case ')': // it's a right paren
        gotParen(ch); // go pop operators
        break;
      default: // must be an operand
        output = output + ch; // write it to output
        break;
      }
    }
    while (!theStack.isEmpty()) {
      output = output + theStack.pop();

    }
    System.out.println(output);
    return output; // return postfix
  }

  public void gotOper(char opThis, int prec1) {
    while (!theStack.isEmpty()) {
      char opTop = theStack.pop();
      if (opTop == '(') {
        theStack.push(opTop);
        break;
      }// it's an operator
      else {// precedence of new op
        int prec2;
        if (opTop == '+' || opTop == '-')
          prec2 = 1;
        else
          prec2 = 2;
        if (prec2 < prec1) // if prec of new op less
        { //    than prec of old
          theStack.push(opTop); // save newly-popped op
          break;
        } else
          // prec of new not less
          output = output + opTop; // than prec of old
      }
    }
    theStack.push(opThis);
  }

  public void gotParen(char ch)
  { 
    while (!theStack.isEmpty()) 
    {
      char chx = theStack.pop();
      if (chx == '(') 
        break; 
      else
        output = output + chx; 
    }
  }
  public int evaluate()
	{
		Stack theStack = new Stack(50);
	int result;
		
		for(int j = 0; j < input.length(); j++)
		{
			char ch = input.charAt(j);
		switch(ch)
		{
		case '0':
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
			theStack.push((char)(ch - '0'));
		case '+':
					int num1; int num2;
			result =  num1 + num2;
			break;
		case '-':
			result = num1 - num2;
			break;
		case '*':
			result = num1 * num2;
			break;
		case '/':
			result = num1 / num2;
			break;
		case '%':
			result = num1 % num2;
			break;
		default:
			result = 0;
		}//end SWITCH
			theStack.push((char) result);
	  }//end FOR
			result = theStack.pop();
			return result;
		
	}
  
  public String getString() throws IOException
  {
	  InputStreamReader isr = new InputStreamReader(System.in);
	  BufferedReader br = new BufferedReader(isr);
	  String s = br.readLine();
	  return s;
  }
  
  
}//end Class

Recommended Answers

All 8 Replies

Make sure to put break after each part of the switch statement. And the reason it's telling you num1 and num2 are wrong is because you declared them from within one part of the switch statement, but then tried to use them within a different part of the switch statement. That is not allowed. Consider this code:

while(whatever){
int number = 0;
number = 5;
}

System.out.println(number);

That print statement is going to cause an error. By declaring number (where I have int number) inside the while loop, I am giving it a range of that while loop. It can't be used outside of that loop. If I wanted to use it outside of that while loop, it has to be declared outside of that while loop:

int number;

while(whatever){
number = 5;
}

System.out.println(number);

For the code below, which you posted, saying input = in is unnecessary. Just say in.length() like I have below. You could further shorten it into one statement also.

public Postfix(String in) {
    int stackSize = in.length();
    theStack = new Stack(stackSize);
  }

I was going to get you a link to read about scope, but they all overcomplicate it. Basically a variable has the scope of where you declare it. So if you declare a variable in a method, it can be used anywhere within that method. If you declare a variable within a loop within a method, it can only be used within that loop. Etc.

I realized that i did forget to set num1 & num2 to theStack.pop2(). Now when i run the program i get Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1. It is something within the pop2() and the evaluate method for num1 but i do not see what the problem is. Here are the error messages i get.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at collection.Stack.pop2(Stack.java:38)
at collection.Postfix.evaluate(Postfix.java:100)
at project.Project22.answer(Project22.java:28)
at project.Project22.test(Project22.java:37)
at testing.MainTester.main(MainTester.java:18)

package collection;
import java.io.*;


public class Postfix {
  private Stack theStack;

  private String input;

  private String output = "";

  public Postfix(String in) {
    input = in;
    int stackSize = input.length();
    theStack = new Stack(stackSize);
  }

  public String doTrans() 
  {
    for (int j = 0; j < input.length(); j++) 
    {
      char ch = input.charAt(j);
      switch (ch) {
      case '+': 
      case '-':
        gotOper(ch, 1); 
        break; //   (precedence 1)
      case '*': // it's * or /
      case '/':
        gotOper(ch, 2); // go pop operators
        break; //   (precedence 2)
      case '(': // it's a left paren
        theStack.push(ch); // push it
        break;
      case ')': // it's a right paren
        gotParen(ch); // go pop operators
        break;
      default: // must be an operand
        output = output + ch; // write it to output
        break;
      }
    }
    while (!theStack.isEmpty()) {
      output = output + theStack.pop();

    }
    System.out.println(output);
    return output; // return postfix
  }

  public void gotOper(char opThis, int prec1) {
    while (!theStack.isEmpty()) {
      char opTop = theStack.pop();
      if (opTop == '(') {
        theStack.push(opTop);
        break;
      }// it's an operator
      else {// precedence of new op
        int prec2;
        if (opTop == '+' || opTop == '-')
          prec2 = 1;
        else
          prec2 = 2;
        if (prec2 < prec1) // if prec of new op less
        { //    than prec of old
          theStack.push(opTop); // save newly-popped op
          break;
        } else
          // prec of new not less
          output = output + opTop; // than prec of old
      }
    }
    theStack.push(opThis);
  }

  public void gotParen(char ch)
  { 
    while (!theStack.isEmpty()) 
    {
      char chx = theStack.pop();
      if (chx == '(') 
        break; 
      else
        output = output + chx; 
    }
  }
  public int evaluate()
	{
		Stack theStack = new Stack(50);
		int result = 0;
		
		for(int j = 0; j < input.length(); j++)
		{
			char ch = input.charAt(j);
			if(ch >= '0' && ch <= '9')
				theStack.push2((int)(ch- '0'));
			else{
				
				int num2 = theStack.pop2();
				int num1 = theStack.pop2();
			
			
		switch(ch)
		{
	/*	case '0':
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
			theStack.push((char)(ch - '0'));
			break; */
			
		case '+':
					
			result =  num1 + num2;
			break;
		case '-':
			result = num1 - num2;
			break;
		case '*':
			result = num1 * num2;
			break;
		case '/':
			result = num1 / num2;
			break;
		case '%':
			result = num1 % num2;
			break;
		default:
			result = 0;
		}//end SWITCH
			theStack.push2(result);
			}
	  }//end FOR
			result = theStack.pop2();
			return result;
		
	}
  
  public String getString() throws IOException
  {
	  InputStreamReader isr = new InputStreamReader(System.in);
	  BufferedReader br = new BufferedReader(isr);
	  String s = br.readLine();
	  return s;
  }
  
  
}//end Class

package collection;
import java.io.*;

public class Stack 
{
	private int maxSize;
	  
    private char[] stackArray;
    private int[] stackArray2;
  
    private int top;
  
    public Stack(int max) 
    {
      maxSize = max;
      stackArray = new char[maxSize];
      stackArray2 = new int[maxSize];
      top = -1;
    }
  
    public void push(char i) 
    {
      stackArray[++top] = i;
    }
    
    public void push2(int j)
    {
    	stackArray2[++top] = j;
    }
  
    public char pop() 
    {
      return stackArray[top--];
    }
    
    public int pop2()
    {
    	return stackArray2[top--];
    }
  
    public char peek() 
    {
      return stackArray[top];
    }
    
    public int peekN(int n)
    {
    	return stackArray[n];
    }
  
    public boolean isEmpty() 
    {
      return (top == -1);
    }
    
    public int size()
    {
    	return top + 1;
    }
    
    public void toString(String s)
    {
    	System.out.print(s);
    	
    	for(int i = 0; i< size(); i++)
    	{
    		System.out.print(peekN(i));
    		System.out.print(' ');
    	}
    	System.out.println(" "); 
    }
  }

also here is the class used to test the code

package project;
import collection.Postfix;
import collection.Stack;
import java.io.*;

public class Project22 
{
	
	public void convert()
	{

		String input = "3+4*5";
	    String output;
	  
	    Postfix theTrans = new Postfix(input);
	    output = theTrans.doTrans(); 
	    System.out.println("Postfix is " + output + '\n');
	}
	
	public void answer()
	{
		String input = "3+4*5";
		int output;
		
		Postfix eval = new Postfix(input);
	    output = eval.evaluate();
		System.out.println("Result = " + output);
		
	}

	public static void test()
	{
		Project22 a = new Project22();
			a.convert();
			a.answer();
		
		
		
	}

}

i got the java.lang.ArrayIndexOutOfBoundsException cleared up I had the top in the stack class set to -1 and i didn't know that a value could not be negative so i set it to zero. Now I just need to calculate the postfix expression correctly.

rtrytgrrwertrytughfe

awe

commented: Do not post useless gibberish. -3

Complete implementation is being done with http://code.google.com/p/expressionoasis/

It is a small framework to evaluate the expressions using RPN. You can get the logic from the source code, as it is open source.

Hello,,

I am using the same code in my program, but there is an ( incompatible types ) error occurs in this line: result = theStack.pop();

public void Evaluate(String x){
         x = postFix;
        int result;
        char answer;
        int num1, num2;
        ListStack EvaluateStack = new ListStack();
        
        for(int i=0; i<x.length(); i++)
        {
            char ch = x.charAt(i);
            
            if(ch >= '0' && ch <= '9')
                EvaluateStack.push((int)(ch- '0'));
            
        switch(ch)
        {
        case '+':
            result =  num1 + num2;
            break;
        case '-':
            result = num1 - num2;
            break;
        case '*':
            result = num1 * num2;
            break;
        case '/':
            result = num1 / num2;
            break;
        
        default:
            result = 0;
        }
            answer = ((char) (result));
            EvaluateStack.push(answer);
      }
            answer = EvaluateStack.pop();
            System.out.println("Evaluation: " + answer );
        
    }

( error occurs in line 36 )

what if the user entered an postfix equation contains operands? eg. x , y ...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.