Archive for January, 2009

108 Part II: Writing Your Own Java Programs

Saturday, January 31st, 2009

108 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.

Chapter 5: Controlling Program Flow with Decision-Making Statements

Saturday, January 31st, 2009

Chapter 5: Controlling Program Flow with Decision-Making Statements 107 Brace yourself The ifstatement in Listing 5-1 has two halves a top half and a bottom half. I have names for these two parts of an ifstatement. I call them the if part (the top half) and the else part (the bottom half). The ifpart in Listing 5-1 seems to have more than one statement in it. I make this happen by enclosing the three statements of the ifpart in a pair of curly braces. When I do this, I form a block. A block is a bunch of statements scrunched together by a pair of curly braces. With this block, three calls to printlnare tucked away safely inside the if part. With the curly braces, the rows of asterisks and the words You winare displayed only when the user s guess is correct. This business with blocks and curly braces applies to the elsepart as well. In Listing 5-1, whenever inputNumberdoesn t equal randomNumber, the computer executes three print/printlncalls. To convince the computer that all three of these calls are inside the elseclause, I put these calls into a block. That is, I enclose these three calls in a pair of curly braces. Strictly speaking, Listing 5-1 has only one statement between the ifand the elsestatements and only one statement after the elsestatement. The trick is that when you place a bunch of statements inside curly braces, you get a block; and a block behaves, in all respects, like a single statement. In fact, the official Java documentation lists blocks as one of the many kinds of statements. So, in Listing 5-1, the block that prints You winand asterisks is a single statement. It s a statement that has, within it, three smaller statements. Indenting if statements in your code Notice how, in Listing 5-1, the printand printlncalls inside the ifstatement are indented. (This includes both the You winand You losestatements. The printand printlncalls that come after the word else are still part of the ifstatement.) Strictly speaking, you don t have to indent the statements that are inside an ifstatement. For all the compiler cares, you can write your whole program on a single line or place all your statements in an artful, misshapen zigzag. The problem is that if you don t indent your statements in some logical fashion, neither you nor anyone else can make sense of your code. In Listing 5-1, the indenting of the printand println statements helps your eye (and brain) see quickly that these statements are subordinate to the overall if/elseflow. In a small program, unindented or poorly indented code is barely tolerable. But in a complicated program, indentation that doesn t follow a neat, logical pattern is a big, ugly nightmare.

For high quality java hosting services please check java web hosting website.

106 Part II: Writing Your Own Java Programs

Saturday, January 31st, 2009

106 Part II: Writing Your Own Java Programs Does inputNumber equal randomNumber? yes no Figure 5-2: ********** You lose. An if *You win.* The random statement is ********** number was… like a fork in the road. Thank you for playing. Sometimes, when I m writing about a condition that s being tested, I slip into using the word expression instead of condition. That s okay, because every condition is an expression. An expression is something that has a value and, sure enough, every condition has a value. The condition s value is either trueor false. (For revealing information about expressions and values like trueand false, see Chapter 4.) The double equal sign In Listing 5-1, in the ifstatement s condition, notice the use of the double equal sign. Comparing two numbers to see whether they re the same isn t the same as setting something equal to something else. That s why the symbol to compare for equality isn t the same as the symbol that s used in an assignment or an initialization. In an ifstatement s condition, you can t replace the double equal sign with a single equal sign. If you do, your program just won t work. (You almost always get an error message when you try to compile your code.) On the other hand, if you never make the mistake of using a single equal sign in a condition, you re not normal. Not long ago, while I was teaching an introductory Java course, I promised that I d swallow my laser pointer if no one made the single equal sign mistake during any of the lab sessions. This wasn t an idle promise. I knew I d never have to keep it. As it turned out, even if I had ignored the first ten times anybody made the single equal sign mistake during those lab sessions, I would still be laser-pointer free. Everybody mistakenly uses the single equal sign several times in his or her programming career. The trick is not to avoid making the mistake; the trick is to catch the mistake whenever you make it.

For high quality website hosting services please check cheap web hosting website.

Chapter 5: Controlling Program Flow with Decision-Making Statements

Saturday, January 31st, 2009

Chapter 5: Controlling Program Flow with Decision-Making Statements 105 Computers aren t much better than coins and human thumbs. A computer mimics the generation of random sequences but, in the end, the computer just does what it s told and does all this in a purely deterministic fashion. So in Listing 5-1, when the computer executes import java.util.Random; int randomNumber = new Random().nextInt(10) + 1; the computer appears to give us a randomly generated number a whole number between 1 and 10. But it s all a fake. The computer just follows instructions. It s not really random, but without bending a computer over backwards, it s the best that anyone can do. Once again, I ask you to take this code on blind faith. Don t worry about what new Random().nextIntmeans until you have more experience with Java. Just copy this code into your own programs and have fun with it. And if the numbers from 1 to 10 aren t in your flight plans, don t fret. To roll an imaginary die, write the statement int rollEmBaby = new Random().nextInt(6) + 1; With the execution of this statement, the variable rollEmBabygets a value from 1to 6. The if statement At the core of Listing 5-1 is a Java ifstatement. This ifstatement represents a fork in the road. (See Figure 5-2.) The computer follows one of two prongs the prong that prints You winor the prong that prints You lose. The computer decides which prong to take by testing the truth or falsehood of a condition. In Listing 5-1, the condition being tested is inputNumber == randomNumber Does the value of inputNumberequal the value of randomNumber? When the condition is true, the computer does the stuff between the condition and the word else. When the condition turns out to be false, the computer does the stuff after the word else. Either way, the computer goes on to execute the last printlncall, which displays Thank you for playing. The condition in an ifstatement must be enclosed in parentheses. However, a line like if (inputNumber == randomNumber)is not a complete statement (just as If I had a hammer isn t a complete sentence). So this line if (inputNumber == randomNumber)shouldn t end with a semicolon.

For high quality website hosting services please check tomcat web hosting website.

104 Part II: Writing Your Own Java Programs

Friday, January 30th, 2009

104 Part II: Writing Your Own Java Programs I can also beef up my program s importdeclarations, as I do in Listings 5-2 and 5-3. Other than that, I have very little leeway. As you read on in this blog, you ll start recognizing the patterns behind these three lines of code, so I don t clutter up this section with all the details. For now, you can just copy these three lines and keep the following in mind: When you import java.util.Scanner, you don t use the word static. Importing Scanneris different from importing System.out. When you import java.lang.System.out, you use the word static. (See Listing 5-1.) For the real story on the word static, see Chapter 10. The name System.in stands for the keyboard. To get characters from someplace other than the keyboard, you can type something other than System.ininside the parentheses. What else can you put inside the parentheses? For some ideas, see Chapter 8. When you expect the user to type an int value (a whole number of some kind), use nextInt(). If you expect the user to type a doublevalue (a number containing a decimal point), use nextDouble(). If you expect the user to type true or false, use nextBoolean(). If you expect the user to type a word (a word like Barry, Java, or Hello), use next(). For an example in which the user types a word, see Listing 5-3. For an example in which the user types a single character, see Listing 6-4 in Chapter 6. For an example in which a program reads an entire line of text (all in one big gulp), see Chapter 8. You can get several values from the keyboard, one after another. To do this, use the myScanner.nextInt()code several times. To see a program that reads more than one value from the keyboard, go to Listing 5-4. Creating randomness Achieving real randomness is surprisingly difficult. Mathematician Persi Diaconis says that if you flip a coin several times, always starting with the head side up, you re likely to toss heads more often than tails. If you toss several more times, always starting with the tail side up, you re likely to toss tails more often than heads. In other words, coin tossing isn t really fair.* * Diaconis, Persi. The Search for Randomness. American Association for the Advancement of Science annual meeting. Seattle. 14 Feb. 2004.

For reliable and cheap web hosting services please check tomcat web hosting website.

Chapter 5: Controlling Program Flow with Decision-Making Statements

Friday, January 30th, 2009

Chapter 5: Controlling Program Flow with Decision-Making Statements 103 Figure 5-1: Two runs of the guessing game. The program in Listing 5-1 plays a guessing game with the user. The program gets a number (a guess) from the user and then generates a random number between 1 and 10. If the number that the user entered is the same as the random number, the user wins. Otherwise, the user loses. In either case, the program tells the user what the random number was. She controlled keystrokes from the keyboard Taken together, the lines import java.util.Scanner; Scanner myScanner = new Scanner(System.in); int inputNumber = myScanner.nextInt(); in Listing 5-1 get whatever number the user types on the keyboard. The last of the three lines puts this number into a variable named inputNumber. If these lines look complicated, don t worry. You can copy these lines almost word for word whenever you want to read from the keyboard. Include the first two lines (the importand Scannerlines) just once in your program. Later in your program, wherever the user types an intvalue, include a line with a call to nextInt(as in the last of the preceding three lines of code). Of all the names in these three lines of code, the only two names that I coined myself are inputNumber and myScanner. All the other names are part of Java. So, if I want to be creative, I can write the lines this way: import java.util.Scanner; Scanner readingThingie = new Scanner(System.in); int valueTypedIn = readingThingie.nextInt();

For reliable and cheap web hosting services please check cheap web hosting website.

102 Part II: Writing Your Own Java Programs

Friday, January 30th, 2009

102 Part II: Writing Your Own Java Programs Making Decisions (Java if Statements) When you re writing computer programs, you re constantly hitting forks in roads. Did the user correctly type his or her password? If yes, let the user work; if no, kick the bum out. So the Java programming language needs a way of making a program branch in one of two directions. Fortunately, the language has a way. It s called an if statement. Guess the number The use of an ifstatement is illustrated in Listing 5-1. Two runs of the program in Listing 5-1 are shown in Figure 5-1. Listing 5-1: A Guessing Game import static java.lang.System.out; import java.util.Scanner; import java.util.Random; class GuessingGame { public static void main(String args[]) { Scanner myScanner = new Scanner(System.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( ********** ); out.println( *You win.* ); out.println( ********** ); } else { out.println( You lose. ); out.print( The random number was ); out.println(randomNumber + . ); } out.println( Thank you for playing. ); } }

For high quality website hosting services please check java web hosting website.

Chapter 5 Controlling Program Flow with Decision-Making Statements

Thursday, January 29th, 2009

Chapter 5 Controlling Program Flow with Decision-Making Statements In This Chapter Writing statements that choose between alternatives Putting statements inside one another Choosing among many alternatives The TV show Dennis the Menace aired on CBS from 1959 to 1963. I remember one episode in which Mr. Wilson was having trouble making an important decision. I think it was something about changing jobs or moving to a new town. Anyway, I can still see that shot of Mr. Wilson sitting in his yard, sipping lemonade, and staring into nowhere for the whole afternoon. Of course, the annoying character Dennis was constantly interrupting Mr. Wilson s peace and quiet. That s what made this situation funny. What impressed me about this episode (the reason why I remember it so clearly even now) was Mr. Wilson s dogged intent in making the decision. This guy wasn t going about his everyday business, roaming around the neighborhood, while thoughts about the decision wandered in and out of his mind. He was sitting quietly in his yard, making marks carefully and logically on his mental balance sheet. How many people actually make decisions this way? At that time, I was still pretty young. I d never faced the responsibility of having to make a big decision that affected my family and me. But I wondered what such a decision-making process would be like. Would it help to sit there like a stump for hours on end? Would I make my decisions by the careful weighing and tallying of options? Or would I shoot in the dark, take risks, and act on impulse? Only time would tell.

For high quality jboss hosting services please check jboss web hosting website.

100 Part II: Writing Your Own Java Programs

Thursday, January 29th, 2009

100 Part II: Writing Your Own Java Programs Figure 4-14: A run of the code in Listing 4-8. Listing 4-8 shows how versatile Java s assignment operators are. With the assignment operators, you can add, subtract, multiply, or divide a variable by any number. Notice how += 5adds 5 to numberOfBunnies, and how *= 2 multiplies numberOfBunniesby 2. You can even use another expression s value (in Listing 4-8, numberExtra) as the number to be applied. The last two lines in Listing 4-8 demonstrate a special feature of Java s assignment operators. You can use an assignment operator as part of a larger Java statement. In the next to last line of Listing 4-8, the operator subtracts 7 from numberOfBunnies, decreasing the value of numberOfBunniesfrom 172to 165. But then the whole assignment business is stuffed into a call to out.println, so the number 165is printed on the computer screen. Lo and behold, the last line of Listing 4-8 shows how you can do the same thing with Java s plain old equal sign. The thing that I call an assignment statement near the start of this chapter is really one of the assignment operators that I describe in this section. So, whenever you assign a value to something, you can make that assignment be part of a larger statement. Each use of an assignment operator does double duty as both a statement and an expression. In all cases, the expression s value equals whatever value you assign. For example, before executing the code out.println (numberOfBunnies -= 7), the value of numberOfBunniesis 172. As a statement, numberOfBunnies -= 7tells the computer to subtract 7 from numberOfBunnies(so the value of numberOfBunniesgoes from 172down to 165). As an expression, the value of numberOfBunnies -= 7is 165. So the code out.println(numberOfBunnies -= 7)really means out. println(165). The number 165 is displayed on the computer screen. For a richer explanation of this kind of thing, see the sidebar, Statements and expressions, earlier in this chapter.

For reliable and cheap web hosting services please check tomcat web hosting website.

Chapter 4: Making the Most of Variables and

Thursday, January 29th, 2009

Chapter 4: Making the Most of Variables and Their Values 99 Assignment operators If you read the preceding section, which is about operators that add 1, you may be wondering whether you can manipulate these operators to add 2 or add 5 or add 1000000. Can you write numberOfBunnies++++and still call yourself a Java programmer? Well, you can t. If you try it, an error message appears when you try to compile your code. So what can you do? As luck would have it, Java has plenty of assignment operators that you can use. With an assignment operator, you can add, subtract, multiply, or divide by anything you want. You can do other cool operations, too. Listing 4-8 has a smorgasbord of assignment operators (the things with equal signs). Figure 4-14 shows the output from running Listing 4-8. Listing 4-8: Assignment Operators import static java.lang.System.out; class UseAssignmentOperators { public static void main(String args[]) { int numberOfBunnies = 27; int numberExtra = 53; numberOfBunnies += 1; out.println(numberOfBunnies); numberOfBunnies += 5; out.println(numberOfBunnies); numberOfBunnies += numberExtra; out.println(numberOfBunnies); numberOfBunnies *= 2; out.println(numberOfBunnies); out.println(numberOfBunnies -= 7); out.println(numberOfBunnies = 100); } }

For high quality website hosting services please check tomcat web hosting website.