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:
Exercises
Question:6 | ISBN:9780136091813 | Edition: 2

Question

Write a method called makeGuesses that guesses numbers between 1 and 50 inclusive until it makes a guess of at least 48. It should report each guess and at the end should report the total number of guesses made. Here is a sample execution:
guess = 43
guess = 47
guess = 45
guess = 27
guess = 49
total guesses = 5

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

package indefinite_loops;

import java.util.Random;

public class GuessCount {

	public int makeGuesses() {

		// use Random class to generate numbers
		Random random = new Random();

		// to store the random value
		int guessedNo;
		// keep track of guess count
		int numOfGuesses = 0;

		// loops infinitely till it met our condition
		while (true) {

			// since nextInt() method include 0 and exclude 50, add 1; now range becomes 1-50
			guessedNo = random.nextInt(50) + 1;
			// increment each time it enter loop
			numOfGuesses++;

			if (guessedNo > 48)
				return numOfGuesses;
		}
	}

	public static void main(String[] args) {

		GuessCount guessCount = new GuessCount();
		int count = guessCount.makeGuesses();
		System.out.println("number of guesses it took to guess number at least 48 is: " +count);
	}

}
Output:

number of guesses it took to guess number at least 48 is: 28

 

0 0

Discussions

Post the discussion to improve the above solution.