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:4 | ISBN:9780136091813 | Edition: 2

Question

Write a method called randomX that prints a lines that contain a random number of “x” characters (between 5 and 20 inclusive) until it prints a line that contains 16 or more characters. For example, the output might look like the following:
xxxxxxx
xxxxxxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxxxxxxx
xxxxxx
xxxxxxxxxxx
xxxxxxxxxxxxxxxxx

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

import java.util.Random;

public class RandomCharacter {

	// pass two interger values as a range
	public void randomX(int origin, int bound) {

		// use Random class to generate numbers between a range
		Random random = new Random();
		int range = bound - origin + 1;
		int randomNum;

		// it continously generate the random numbers till one time it generate 16 or
		// more
		while (true) {

			// nextInt gives the random number in the bounded range. we add origin value to
			// get
			// a random number between those two.
			randomNum = random.nextInt(range) + origin;
			// run through loop
			for (int i = 1; i <= randomNum; i++) {
				System.out.print("*");
			}
			System.out.println();
			// if it met our conditions, return
			if (randomNum >= 17)
				return;
		}

	}

	public static void main(String[] args) {

		new RandomCharacter().randomX(5, 20);

	}

}

Output:

*********
*************
************
*********
****************
********
*******
**************
*******************

 

0 0

Discussions

Post the discussion to improve the above solution.