It seems a little more compact. This, of course, requires fewer lines and conventions. The key is to add default behavior, and each minus sign that you encounter changes the sign of what you want to add; if you remember the reset sign after each addition.
public static int eval(String s){ int result = 0; int sign = 1; for(int i = 0; i < s.length(); i++){ char current = s.charAt(i); switch (current) { case '+': break; case '-': sign *= -1; break; default: result += sign * Character.getNumericValue(current); sign = 1; break; } } return result; }
As a side note, I donβt think your results give the correct results for adding a negative value, like β-4 -3β. Your code produces 1, not the correct value 7. On the other hand, mine allows you to express expressions such as "5 + - + - 3", which will lead to result 8 (I assume this is correct? :). However, you did not specify validation as a requirement, and none of us validates consecutive numbers, alpha characters, spaces, etc. If we assume that the data is formatted correctly, the above implementation should work. I do not see how it might be useful to add data structures (like queues). I also assume only addition and subtraction.
These test cases give the following results:
System.out.println(eval("1+2+3+4")); System.out.println(eval("1--3")); System.out.println(eval("1+-3-2+4+-3")); 10 4 -3
source share