/**
 * A program to demonstrate the proper way to find the average of two
 * known-to-be-positive int values.
 * 
 * @author Mark Young (A00000000)
 */
public class OverflowError {

    public static void main(String[] args) {
        // describe yourself
        System.out.println("\n"
                + "Demonstration of overflow error in calculating "
                + "the midpoint of two large\npositive numbers.\n");
        
        // create large numbers
        int hi = 2000000000;
        int lo = 1000000000;
        
        // report them to the user
        System.out.printf("%s == %,d%n", "hi", hi);
        System.out.printf("%s == %,d%n", "lo", lo);
        System.out.println();
        
        // show the error
        System.out.printf("%s %n\t== %s %n\t== %s %n\t== %,d%n", 
                "(hi + lo) / 2",
                String.format("(%,d + %,d) / 2", hi, lo),
                String.format("%,d / 2", (hi + lo)),
                (hi + lo) / 2);
        System.out.println();
        
        // show how the error is avoided
        System.out.printf("%s %n\t== %s %n\t== %s %n\t== %s %n\t== %,d%n", 
                "lo + (hi - lo) / 2",
                String.format("%,d + (%,d - %,d) / 2", lo, hi, lo),
                String.format("%,d + (%,d / 2)", lo, hi - lo),
                String.format("%,d + %,d", lo, (hi - lo) / 2),
                lo + (hi - lo) / 2);
        System.out.println();
    }

}
