124 Part II: Writing Your Own Java Programs (My space web page)

124 Part II: Writing Your Own Java Programs Repeating Instructions Over and Over Again (Java while Statements) Here s a guessing game for you. The computer generates a random number from 1 to 10. The computer asks you to guess the number. If you guess incorrectly, the game continues. As soon as you guess correctly, the game is over. The program to play the game is shown in Listing 6-1, and a round of play is shown in Figure 6-1. Listing 6-1: A Repeating Guessing Game import static java.lang.System.out; import java.util.Scanner; import java.util.Random; class GuessAgain { public static void main(String args[]) { Scanner myScanner = new Scanner(System.in); int numGuesses = 0; int randomNumber = new Random().nextInt(10) + 1; out.println( ************ ); out.println( Welcome to the Guessing Game ); out.println( ************ ); out.println(); out.print( Enter an int from 1 to 10: ); int inputNumber = myScanner.nextInt(); numGuesses++; while (inputNumber != randomNumber) { out.println(); out.println( Try again… ); out.print( Enter an int from 1 to 10: ); inputNumber = myScanner.nextInt(); numGuesses++; } out.print( You win after ); out.println(numGuesses + guesses. ); } }
You need web hosting, easy to use web template and great support. What else could I ask for?All of our reseller accounts include free web hosting templates just check web hosting templates for more information.

Leave a Reply