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);
}
}
            Asked
            
        
        
            Active
            
        
            Viewed 38 times
        
    -1
            
            
         
    
    
        Ivan
        
- 8,508
- 2
- 19
- 30
 
    
    
        Alishan Ahmed
        
- 11
- 3
- 
                    Indexes in array are from `0` to `length - 1` – Ivan Aug 23 '18 at 21:01
- 
                    Check the values you attempt to split – akortex Aug 23 '18 at 21:01
2 Answers
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--) 
{
 
    
    
        John Ciociola
        
- 97
- 7
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
 
    
    
        Rosa Mohammadi
        
- 46
- 1