In: Computer Science
PLEASE CODE IN JAVA
In this assignment you will write a program in that can figure out a number chosen by a human user. The human user will think of a number between 1 and 100. The program will make guesses and the user will tell the program to guess higher or lower.
Requirements
The purpose of the assignment is to practice writing functions. Although it would be possible to write the entire program in the main function, your solution should be heavily structured. The main function must look like this:
public static void main(String[] args) {
do {
playOneGame();
} while (shouldPlayAgain());
}
The playOneGame function should have a return type of void. It should implement a complete guessing game on the range of 1 to 100.
The shouldPlayAgain function should have a boolean return type. It should prompt the user to determine if the user wants to play again, read in a character, then return true if the character is a ‘y’, and otherwise return false.
In addition, you should implement the helper functions getUserResponseToGuess, and getMidpoint. They should be invoked inside your playOneGame function.
getUserResponseToGuess. This function should prompt the user with the phrase “is it <guess>? (h/l/c): “ with the value replacing the token <guess>. It should return a char. The char should be one of three possible values: ‘h’, ‘l’, or ‘c’. It should have the following signature:
public static char getUserResponseToGuess(int guess)
getMidpoint. This function should accept two integers, and it should return the midpoint of the two integers. If there are two values in the middle of the range then you should consistently chose the smaller of the two. It should have the following signature:
public static int getMidpoint(int low, int high)
CHECK BELOW EXAMPLE IT IS VERY EASY TO UNDERSTAND AND FOR A GUESS NUMBER IT WILL SAY HIGH OR LOW THAN THAT NUMBER IF YES IT SAYS CORRECT JAVA PROGRAM : import java.util.Random; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); Random random = new Random(); long from = 1; long to = 100; int randomNumber = random.nextInt(to - from + 1) + from; int guessedNumber = 0; System.out.printf("The number is between %d and %d.\n", from, to); do { System.out.print("Guess what the number is: "); guessedNumber = scan.nextInt(); if (guessedNumber > randomNumber) System.out.println("Your guess is too high!"); else if (guessedNumber < randomNumber) System.out.println("Your guess is too low!"); else System.out.println("You got it!"); } while (guessedNumber != randomNumber); } }
Demonstration:
The number is between 1 and 100. Guess what the number is: 50 Your guess is too high! Guess what the number is: 25 Your guess is too high! Guess what the number is: 17 Your guess is too high! Guess what the number is: 10 Your guess is too high! Guess what the number is: 5 Your guess is too low! Guess what the number is: 7 You got it!