You always do a positive sum += on operator -.
But how about using the Stream-API instead?
IntStream.of(1, 2, 3, 4, 5)
.reduce(operatorFunction('-'))
.ifPresent(System.out::println);
with the following IntBinaryOperator-returning function:
static IntBinaryOperator operatorFunction(char operator) {
if (operator == '-') {
return (int1, int2) -> int1 - int2;
}
return (int1, int2) -> int1 + int2;
}
which prints -13 as you would expect. This is all you need. Note that you could also use IntStream.sum to achieve a simple sum. With the operatorFunction however you could also add * or ÷ later if you wish.
Another way to write the above code (with intermediate values):
int[] yourInputArray = {1, 2, 3, 4, 5};
char operator = '-';
OptionalInt = Stream.of(yourInputArray)
.reduce(operatorFunction(operator));
From here you can call orElse(0) or throw an exception with orElseThrow(() -> ...), etc. Just have a look at the OptionalInt-javadoc for your options. As soon as you move away from the primitive int you may want to exchange the code by using Stream, BinaryOperator<Integer> and Optional<Integer>.
By the way, there is also an IndexOutOfBoundException in your current code. But why messing with indexes and arrays, if you can use Streams and so few lines of code?