-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); } } 
2
  • Indexes in array are from 0 to length - 1 Commented Aug 23, 2018 at 21:01
  • Check the values you attempt to split Commented Aug 23, 2018 at 21:01

2 Answers 2

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--) { 
Sign up to request clarification or add additional context in comments.

1 Comment

@Ivan yeah I just caught that while fixing a typo, thanks!
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--)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.