Chapter 5: Controlling Program Flow with Decision-Making Statements (Web hosting java)

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.
Here java web hosting you will find professional-grade java web hosting at affordable prices.

Leave a Reply