/* * T05n01.java -- Using IFs to test pre- and post-conditions. * * Assertions have been added to Java for the purpose of giving Java * programmers a slightly nicer way to check for internal logic * errors that require program termination. This program demonstrates * the traditional way of handling such problems, using IF statements * and manually terminating the program. * * See T05n02.java for the same program with assertions. * * Note for IDE (Eclipse, Netbeans, TextPad, etc.) users: This program * gets input from the command line. This works great if you're running * the program from a terminal window, but when running from within an * IDE you'll need to figure out how to get your IDE to accept command * line arguments. Consult your IDE's documentation. */ import java.io.*; public class T05n01 { /* Find the smallest power of two greater than the * given positive integer ceiling. * This version does the testing the old fashioned way, * without all that fancy assertion stuff. * Pre-condition: limit > 0 * Post-condition: returns smallest power of two > limit */ static int smallestPowerOf2 (int limit) { int product = 1; if (limit <= 0) { System.err.println("Pre-condition Error: In smallestPowerOf2, " + "limit must be > 0!"); System.exit(1); } for (; product <= limit; product *= 2); // good programming style? if (product/2 > limit) { System.err.println("Post-condition Error: In smallestPowerOf2, " + product + "is NOT is smallest " + "power of 2 greater than " + limit + "."); System.exit(1); } return product; } public static void main (String [] args) { int limit, powerOf2; if (args.length < 1) { System.out.println("\nUsage: Provide a positive integer on the" + " command line, and I'll find\nthe first" + " power of 2 that exceeds it.\n\n"); System.exit(1); } limit = Integer.parseInt(args[0]); powerOf2 = smallestPowerOf2(limit); System.out.println("smallestPowerOf2 says that the smallest power of 2 " + "greater than " + limit + " is " + powerOf2 + "."); } }