CASE STUDY #4: A Number Guessing Game -- Building a Program Step By Step
Step One: Let's try a different method for finding a random number -- this time from 1 to 1000.
import java.util.Scanner;Suggestions for Continuing to Upgrade Your Code
public class NumberGuessingGame {
public static void main(String[] args)
{
int secretNumber;
secretNumber = (int) (Math.random() * 999 + 1);
System.out.println("Secret number is " + secretNumber); // to be removed later
Scanner keyboard = new Scanner(System.in);
int guess;
do {
System.out.print("Enter a guess: ");
guess = keyboard.nextInt();
System.out.println("Your guess is " + guess);
if(guess == secretNumber)
{
System.out.println("Your guess is correct! Congratulations!");
}
if (guess < secretNumber)
{
System.out.println("Your guess is smaller than the secret number.");
}
if (guess > secretNumber)
{
System.out.println("Your guess is larger than the secret number.");
}
} while (guess != secretNumber);
}
}
- Add comments and labels [obviously]
- Create a little title text graphic to display at the beginning of your program.
- Display "Guess #" in front of [or behind] each "Enter a guess" prompt.
- Limit the number of guesses a user gets -- and you might even have it display something like "Guess 3 of 10".
No comments:
Post a Comment