108 Part II: Writing Your Own Java Programs
Saturday, January 31st, 2009108 Part II: Writing Your Own Java Programs When you write ifstatements, you may be tempted to chuck all the rules about curly braces out the window and just rely on indentation. Unfortunately, this seldom works. If you indent three statements after the word else and forget to enclose those statements in curly braces, the computer thinks that the else part includes only the first of the three statements. What s worse, the indentation misleads you into believing that the elsepart includes all three statements. This makes it more difficult for you to figure out why your code isn t behaving the way you think it should behave. So watch those braces! Elseless in Ifrica Okay, so the title of this section is contrived. Big deal! The idea is that you can create an ifstatement without the elsepart. Take, for instance, the code in Listing 5-1. Maybe you d rather not rub it in whenever the user loses the game. The modified code in Listing 5-2 shows you how to do this (and Figure 5-3 shows you the result). Listing 5-2: A Kinder, Gentler Guessing Game import static java.lang.System.in; import static java.lang.System.out; import java.util.Scanner; import java.util.Random; class DontTellThemTheyLost { public static void main(String args[]) { Scanner myScanner = new Scanner(in); out.print( Enter an int from 1 to 10: ); int inputNumber = myScanner.nextInt(); int randomNumber = new Random().nextInt(10) + 1; if (inputNumber == randomNumber) { out.println( *You win.* ); } out.println( That was a very good guess
); out.print( The random number was ); out.println(randomNumber + . ); out.println( Thank you for playing. ); } } The ifstatement in Listing 5-2 has no elsepart. When inputNumberis the same as randomNumber, the computer prints You win.When inputNumber is different from randomNumber, the computer doesn t print You win.
For high quality website hosting services please check tomcat web hosting website.