In: Computer Science
guessing game in Java.
It will have a guess input used for guessing the random number that is generated from 1 - 100.
When the user makes a guess it will tell them if the number is lower or higher than the guess.
There is also a choice to give up which then reveals the correct number.
The last choice will be new game which resets the random number.
Last, the program should keep counts of tries.
When the user guesses the correct answer, the program will say “You got in in 5 tries” if the user took guesses to get it.
The number of tries should reset to 0 for each new game.
Add a simple dialog that tells the user when he guesses correctly.
CODE
import java.util.*;
public class Main
{
public static void main(String[] args) {
Random rand = new Random();
Scanner scan = new
Scanner(System.in);
int newgame = 1;
while(newgame==1){
int number =
rand.nextInt(100);
System.out.println("Lets start new
game");
int guess = -1;
int attempts = 0;
//we put a while loop here because
program will continue till correct answer is not guessed
while(guess!=number){
System.out.println("Please enter
your guess");
guess = scan.nextInt();
if(guess<number){
System.out.println("Your guess is
less than the number");
attempts++;
}
else if(guess>number){
System.out.println("Your guess is
greater than the number");
attempts++;
}
}
if(guess==number){
System.out.println("Congratulations!! You got in "+ attempts+"
tries");
System.out.println("Do you wanna
play again?\n Yes, then press 1\n No, then press 0");
//while loop will terminate if no
is choosen, as while continues till newgame==1;
newgame = scan.nextInt();
}
}
}
}
ALGORITHM
1. First import java.util.*;
It will be needed for Scanner class and Random
class.
2. We make a while loop that will not terminate till you keep on
asking to play new game.
number variable contains random number;
3. Inside this we again create a while loop which will not
terminate till you have guessed correct.
guess variable represents your guess;
attempts counts your wrong tries;
4. After the correct guess there is dialog that if player wants to
play a new game.
I am attaching screenshot of output with my answer.