/* * T05n02.java -- Using Assertions 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, and the assertion * way of doing it. Assertions can be used to check all post-conditions, * pre-conditions of private methods, as well as other logically problems. * Remember that it is NOT appropriate to use assertions to test * parameters of a public method of a shared class; throw a more * meaningful exception instead. * * Special Compilation Instructions: To use Java's assertion feature, * you must: * * Be using Java 1.4 or higher * * Execute with the flag "-ea" or "-enableassertions" * Ex: java -ea T05n02 * Without "-ea", the program will run as if the assertion statements * don't exist. * * For you IDE users, again, you'll need to find out how to supply that "-ea" * flag when you execute your code. */ import java.io.*; public class T05n02 { /* Find the smallest power of two greater than the * given positive integer ceiling. * This version uses assertions to check pre-/post-conditions. * Pre: limit > 0 * Post: returns smallest power of two greater than limit */ static int smallestPowerOf2 (int limit) { int product = 1; assert limit > 0 : "\n\nPre-condition Error: In smallestPowerOf2, " + "limit must be > 0!\n"; while (product <= limit) { product *= 2; // clearer than the for loop in T05n01? } assert product/2 <= limit : "\n\nPost-condition Error: In " + "smallestPowerOf2, " + product + "is NOT is smallest power " + "of 2 greater than " + limit + ".\n"; return product; } public static void main (String [] args) { int limit, powerOf2; assert args.length > 0 : "\n\nUsage: Provide a number on the command " + "line, and I'll find the first\npower of 2 " + "that exceeds it.\n\n"; limit = Integer.parseInt(args[0]); powerOf2 = smallestPowerOf2(limit); System.out.println("smallestPowerOf2 says that the smallest power of 2 " + "greater than " + limit + " is " + powerOf2 + "."); } }