CS 3230 - Lab 2

"Guess a Number" program

This lab is going to be a little different than the previous "step-by-step" lab from last week. In this lab, I will give you some specifications and you will need to write a program that meets those specifications. Don't worry, I'll give you some hints to help you.

Specifications

A user tries to guess a number from 1 to 100. He gets 10 guesses to do it.

Detail

  1. When the program starts, it will pick a random number from 1 to 100 and initialize the number of guesses to 10.
  2. The user is presented with a prompt that reads "Guess a number between 1 and 100 (10 guesses left)".
  3. As the user enters guesses, it will print whether the number is too high or too low and decrement the number of guesses.
  4. The program will re-display the prompt from step #2, updated with the number of guesses left.
  5. If the user guesses the number, the program will print "You guessed it!", if the user didn't get it in 10 tries, the program will print "Sorry, you ran out of guesses. The number was [num]". (Where [num] is the number randomly generated by the program.)
  6. Lastly, the program will prompt the user whether he wants to play again. If so, it will repeat the previous steps. If not, the program will exit.

Output

Because a picture is worth a thousand words, here's an example of output from a working program:

Guess a number between 1 and 100 (10 guesses left): 50
Too low, try a higher number
Guess a number between 1 and 100 (9 guesses left): 75
Too low, try a higher number
Guess a number between 1 and 100 (8 guesses left): 87
Too low, try a higher number
Guess a number between 1 and 100 (7 guesses left): 93
Too high, try a lower number
Guess a number between 1 and 100 (6 guesses left): 90
You guessed it!
Want to play again? (y/n) n

Stuff I'm Expecting To See

Questions and Answers

How do I generate a random number from 1 to 100?

int number = (int)(Math.random() * 100) + 1;

No need to import anything.

How do I write a message to stdout?

System.out.println("message...");

How do I print the value of a variable to stdout?

int var = 5;
System.out.println("var=" + var);

How do I read from stdin?

Use the EasyInput class that I wrote for you. The I/O classes in Java are a bit bewildering, this helper class should make life easier for you. Using it is simple:

String str = EasyInput.readString();
char c = EasyInput.readChar();
int i = EasyInput.readInt();
double d = EasyInput.readDouble();

Just drop the EasyInput.java file in the same directory as your lab assignment, compile your lab and it will all just magically work; no need to import anything. Piece of cake. The source code is there if you want to look at it.