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 in calculating "
13: + "the midpoint of two large\npositive numbers.\n");
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: System.out.println();
23:
24: // show the error
25: System.out.printf("%s %n\t== %s %n\t== %s %n\t== %,d%n",
26: "(hi + lo) / 2",
27: String.format("(%,d + %,d) / 2", hi, lo),
28: String.format("%,d / 2", (hi + lo)),
29: (hi + lo) / 2);
30: System.out.println();
31:
32: // show how the error is avoided
33: System.out.printf("%s %n\t== %s %n\t== %s %n\t== %s %n\t== %,d%n",
34: "lo + (hi - lo) / 2",
35: String.format("%,d + (%,d - %,d) / 2", lo, hi, lo),
36: String.format("%,d + (%,d / 2)", lo, hi - lo),
37: String.format("%,d + %,d", lo, (hi - lo) / 2),
38: lo + (hi - lo) / 2);
39: System.out.println();
40: }
42: }