-1
import java.util.Scanner;
import java.util.Stack;

class Postfix2 {
public static void postfix2(String str)
{
    String s[] = str.split("");
    Stack <String>st = new Stack<String>();
    String result = "";
    String num1 = "", num2 = "";

    for (int i=s.length; i>0; i--) 
    {

        if (!"+".equals(s[i]) && !"-".equals(s[i]) && !"*".equals(s[i]) && !"/".equals(s[i]))
            st.push(s[i]);
        else
        {
            num1 = st.pop();
            num2 = st.pop();
            result = num1 + num2 + s[i];
            st.push(result);
        }
    }

    System.out.println("Result: "+st.pop());
}

public static void main(String[] args) 
{
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter input string.");
    String str = sc.next();
    postfix2(str);
}
}
Ivan
  • 8,508
  • 2
  • 19
  • 30

2 Answers2

1

i needs to be equal to (s.length - 1) to account for the fact that the indexes start at zero in the first for loop.

Also, you may want to change the condition to i >= 0 since there will be an index of 0 as well unless you skipped that on purpose.

for (int i=(s.length -1); i>0; i--) 
{
1

In the for loop you are starting to index outside of the length of the array. For example, if the array s = [x,y,z], s.length returns 3, but the last element z has index of 2 since elements are indexed starting from 0.

Try changing this for (int i=s.length; i>0; i--)

to this: for (int i=s.length-1; i>=0; i--)

GBlodgett
  • 12,704
  • 4
  • 31
  • 45