Number Guess Game
807606Apr 22 2007 — edited Apr 22 2007i am trying to Create a guessing game that allows you to enter the number of numbers in the guessing game. The game will randomly pick a number in the range provided and then allow you to guess the number. The game will keep track of the number of guesses and tell you what percentage of the time you guessed incorrectly.
Sample Input/Output:
Guessing Game - how many numbers? 5
Enter a number between 1 and 5: 1
Enter a number between 1 and 5: 2
Enter a number between 1 and 5: 3
It took 3 guesses to guess 3.
You guessed wrong 40 percent of the time.
Do you want to play again? y
Guessing Game - how many numbers? 5
Enter a number between 1 and 5: -3
Number out of range!
Enter a number between 1 and 5: 9
Number out of range!
Enter a number between 1 and 5: 1
Enter a number between 1 and 5: 2
Enter a number between 1 and 5: 3
Enter a number between 1 and 5: 4
It took 4 guesses to guess 4 .
You guessed wrong 60 percent of the time.
Do you want to play again? y
Guessing Game - how many numbers? 20
Enter a number between 1 and 20: 1
Enter a number between 1 and 20: 2
Enter a number between 1 and 20: 3
Enter a number between 1 and 20: 4
Enter a number between 1 and 20: 5
Enter a number between 1 and 20: 6
Enter a number between 1 and 20: 7
Enter a number between 1 and 20: 8
It took 8 guesses to guess 8 .
You guessed wrong 35 percent of the time.
Do you want to play again? n
Here's my code so far. What i cant figure out is how to loop it so it will play again when i enter y or end when i enter n.
public class lab14c
{
public void run()
{
Scanner keyboard = new Scanner(in);
Random generator = new Random();
int guess;
int numTries=0;
out.print("Guess Game - how many numbers? ");
int num = keyboard.nextInt();
int randomNum = (int)(1+Math.random()*num);
do{
out.print("Enter a number between 1 and " num " ");
guess = keyboard.nextInt();
numTries++;
if(guess<1 || guess>num)
{
out.println("Number out of range!");
}
}while(guess!=randomNum);
if(randomNum==guess)
{
int percent = ((numTries-1)*100)/(num);
out.println("\nIt took " numTries " guesses to guess " randomNum ".");
out.println("You guessed wrong " percent " percent of the time.");
out.print("\nDo you want to play again? ");
String a = keyboard.next();
}
}
public static void main(String args[])
{
lab14c test = new lab14c();
test.run();
}
}