Disclaimer: Your source code has multiple problems, but in order to keep it simple I am going to ignore most of them now and will just explain the reasons for your current problems and suggest fixes for them only.
If you check the array outputs from your main
method, you see that the addition/subtraction results look good, i.e. the problem is not located in the calculation routines but in the print routine. There you have
- duplicate code: The
for
loops printing the positive/negative numbers are identical.
- a cosmetic problem: One leading zero is always printed.
- a logical error: You check for two consecutive zeroes in order to determine where leading zeroes end and the actual number begins. But you forget that
- within a number there can also be duplicate zeroes, e.g. within 10098 or -9900. This explains why 10098 is printed as 1098: You are suppressing the first zero from being printed.
- if there is a zero in the last array element (e.g. 9900) you cannot check the (non-existent) subsequent element without causing an
ArrayIndexOutOfBoundsException
. This explains why you get the exception for -9900.
Now what can/should you do?
- Eliminate the redundant
for
loop. You can use the same loop to print both positive and negative numbers.
- Use a
boolean
flag in order to remember if you are still looping through leading zeroes or not.
You can change your print method like so:
public static void print(int[] result, String operation) {
System.out.print(operation.charAt(0) == '-' ? "Difference = " : "Sum = ");
if (result[0] == 9) {
result = negate(result);
System.out.print("-");
}
boolean leadingZero = true;
for (int i = 0; i < result.length; i++) {
if (leadingZero) {
if (result[i] == 0)
continue;
leadingZero = false;
}
System.out.print(result[i]);
}
System.out.println(leadingZero ? "0" : "");
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…