In: Computer Science
In JAVA, write a number guessing game that randomly assigns a integer between one and twenty for the user to guess.
Write three methods to make this particular program work.
1. Have a method which generates a random number and returns the value to the main (stored as a variable)
2. Have a method which prompts the user for a guess. Return the guess to the main.
3. Evaluate the guess and the random "secret" number by parameters, and then have it evaluate if the guess is correct. RETURN A STRING to let the user know if the guess was correct, too high, or too low.
Use a nested loop in main. Ask the user if they would like to play again. Use an inner loop that continually calls the third method until the guess is correct.
Code:-
import java.lang.*;
import java.util.*;
class game{
public static int generator(){
Random rand = new Random();
//random number generator
return rand.nextInt(20);
//returning random number
}
public static int userguess(){ //function to take
input from user
System.out.print("Enter your Guess:
");
Scanner scan=new
Scanner(System.in); //scanner
int guess=scan.nextInt(); //taking
input from user
return guess; //returning
guess
}
public static String evaluate(int rand,int guess){
//function to return string
if(guess>rand) //if guess is
higher than random number
return "TOO
HIGH";
else if(guess<rand) //if guess
is lower than random number
return "TOO
LOW";
else //if guess and random number
are equal
return
"CORRECT";
}
public static void main(String[] args) { //main
function
while(true){ //loop until use enter
want to exit by clicking n
int
rand=generator(); //calling function
while(true){
//loop until user guess the correct number
int guess=userguess();
String eval=evaluate(rand,guess); //calling
function
System.out.println(eval); //calling
function
if(eval.equals("CORRECT")) //if guess is
correct
break;
}
System.out.print("Do You Want to play Again(y/n): "); //enter n for
stop
Scanner scan=new
Scanner(System.in);
char
ch=scan.nextLine().charAt(0); //taking input from user
if(ch=='n') //if
user enters n
break; //breaking the loop
}
}
}
Output:-