public class OverflowError
1: /**
2: * A program to demonstrate the proper way to find the average of two
3: * known-to-be-positive int values.
4: *
5: * @author Mark Young (A00000000)
6: */
7: public class OverflowError {
9: public static void main(String[] args) {
10: // describe yourself
11: System.out.println("\n"
12: + "Demonstration of overflow error "
13: + "in calculating the midpoint of two positive numbers.");
14:
15: // create large numbers
16: int hi = 2000000000;
17: int lo = 1000000000;
18:
19: // report them to the user
20: System.out.printf("%s == %,d%n", "hi", hi);
21: System.out.printf("%s == %,d%n", "lo", lo);
22:
23: // show the error
24: System.out.printf("%s == %s == %,d%n",
25: "(hi + lo) / 2",
26: String.format("(%,d + %,d) / 2", hi, lo),
27: (hi + lo) / 2);
28:
29: // show how the error is avoided
30: System.out.printf("%s == %s == %,d%n",
31: "lo + (hi - lo) / 2",
32: String.format("%,d + (%,d - %,d) / 2", lo, hi, lo),
33: lo + (hi - lo) / 2);
34: }
36: }