/** * Decisions.java * * @author Jeff Ondich * * This program illustrates if/else statements. * * 1. Compile the class and run main. * * 2. Read the code carefully and try various integers to make all of the * different messages get printed. * * 3. In the bottles-of-beer section, what happens if you remove the curly braces? * (Try removing the curly braces, compiling, and then running it with some * number other than 99 to see the problem.) * * 4. if/else statements are not especially difficult to understand, but * there are several important details that you need to know. Make sure to * study this code carefully enough that you are confident you understand * the roles of if, else, else if, &&, ||, and {}. */ import javabook.*; class Decisions { public static void main( String[] args ) { // Get ready to talk to the us. MainWindow mw = new MainWindow(); mw.setVisible( true ); mw.toFront(); OutputBox out = new OutputBox( mw ); out.setVisible( true ); out.toFront(); InputBox in = new InputBox( mw ); // Ask for a number. int j = in.getInteger( "Number, please:" ); // A simple "if-else" statement. if( j % 2 == 0 ) out.printLine( j + " is even." ); else out.printLine( j + " is odd." ); // You can make a stack of if/else if/else if/... to choose among // many cases. if( j == 1 ) out.printLine( j + " is the loneliest number." ); else if( j == 2 ) out.printLine( j + " is dualicious." ); else if( j == 1729 ) out.printLine( j + " is the lowest integer that can be written of the sum of two cubes in two different ways." ); else out.printLine( j + " seems so ordinary." ); // You don't need an else if you don't want it. if( j < 0 ) out.printLine( j + " is negative." ); // You can make more complicated comparisons using && for "and" // and || for "or". if( j > 83 && j < 89 ) out.printLine( j + " is so pleasingly close to 86." ); // If the "body" of an if statement (the thing to do if the condition // is met) is more than one line, you need to put curly braces around it. if( j == 99 ) { out.printLine( j + " bottles of beer on the wall" ); out.printLine( j + " bottles of beer" ); out.printLine( "take one down, pass it around" ); out.printLine( (j-1) + " bottles of beer on the wall" ); } } }