SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Program Logic And Indefinite Loops
Exercise:
Programming Projects
Question:4 | ISBN:9780136091813 | Edition: 2

Question

Write a program that plays a reverse guessing game with the user. The user thinks of a number between 1 and 10, and the computer repeatedly tries to guess it by guessing random numbers. It’s fine for the computer to guess the same random number more than once. At the end of the game, the program reports how many guesses it made. Here is a sample execution:
This program has you, the user, choose a number between 1 and 10. Then I, the computer, will try my best to guess it.
Is it 8? (y/n) n
Is it 7? (y/n) n
Is it 5? (y/n) n
Is it 1? (y/n) n
Is it 8? (y/n) n
Is it 1? (y/n) n
Is it 9? (y/n) y
I got your number of 9 correct in 7 guesses.

For an added challenge, consider having the user hint to the computer whether the correct number is higher or lower than the computer’s guess. The computer should adjust its range of random guesses on the basis of the hint.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program:

import java.util.*;
public class Ch05PP04 {
	public static void main(String[] args) {
		int randNum;
		char userHint;
		char userAns;		
		int guesses = 0;
		
		Scanner scnr = new Scanner(System.in);
		Random rand = new Random();
		
		System.out.println("This program has you, the user, choose a number");
		System.out.println("between 1 and 10. Then I, the computer, will try");
		System.out.println("my best to guess it.");
				
		randNum = 1 + rand.nextInt(10);
		guesses++;
		
		System.out.print("Is it " + randNum + "? (y/n) ");
		userAns = scnr.next().charAt(0);		
		
		while(userAns != 'y') {
			System.out.print("Is your number higher than " + randNum + "? (y/n) ");
			userHint = scnr.next().charAt(0);
			
			if(userHint == 'y') {
				randNum = 1 + randNum + rand.nextInt(10 - randNum);
			}
			else {
				randNum = 1 + rand.nextInt(randNum - 1);
			}
			guesses++;
			
			System.out.print("Is it " + randNum + "? (y/n) ");
			userAns = scnr.next().charAt(0);
		}
		
		System.out.println("I got your number of " + randNum + " correct in " + guesses + " guesses.");
	}
}

Output:

0 0

Discussions

Post the discussion to improve the above solution.