102 Part II: Writing Your Own Java Programs (Paypal hosting)

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. ); } }
If you are looking quality, fast, secure and reliable web hosting with PHP service at an affordable price, check php5 hosting services.

Leave a Reply