Java hosting - 126 Part II: Writing Your Own Java Programs

126 Part II: Writing Your Own Java Programs When you look over Listing 6-1, you see the code that does all this work. At the core of the code is a thing called a while statement (also known as a while loop). Rephrased in English, the whilestatement says: while the inputNumber is not equal to the randomNumber keep doing all the stuff in curly braces: { } The stuff in curly braces (the stuff that repeats over and over again) is the code that prints Try again, Enter an int . . ., gets a value from the keyboard and adds 1 to the count of the user s guesses. When you re dealing with counters, like numGuessesin Listing 6-1, you may easily become confused and be off by 1 in either direction. You can avoid this headache by making sure that the ++statements stay close to the statements whose events you re counting. For example, in Listing 6-1, the variable numGuessesstarts off with a value of 0. That s because, when the program starts running, the user hasn t made any guesses. Later in the program, right after each call to myScanner.nextInt, is a numGuesses++ statement. That s how you do it you increment the counter as soon as the user enters another guess. The statements in curly braces are repeated as long as inputNumber != randomNumberkeeps being true. Each repetition of the statements in the loop is called an iteration of the loop. In Figure 6-1, the loop undergoes three iterations. (If you don t believe that Figure 6-1 has exactly three iterations, count the number of Try againprintings in the program s output. A Try againappears for each incorrect guess.) When, at long last, the user enters the correct guess, the computer goes back to the top of the whilestatement, checks the condition in parentheses, and finds itself in double negative land. The not equal (!=) relationship between inputNumberand randomNumberno longer holds. In other words, the whilestatement s condition, inputNumber != randomNumber, has become false. Because the whilestatement s condition is false, the computer jumps past the whileloop and goes on to the statements just below the whileloop. In these two statements, the computer prints You win after 4 guesses. With code of the kind shown in Listing 6-1, the computer never jumps out in mid-loop. When the computer finds that inputNumberisn t equal to randomNumber, the computer marches on and executes all five statements inside the loop s curly braces. The computer performs the test again (to see whether inputNumberis still not equal to randomNumber) only after it fully executes all five statements in the loop.
Hosting services offered by our company comes with free domain name if you pay at yearly basis. Find out more at New Orleans Web Hosting services.

Leave a Reply