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

Question

Write a method called randomLines that prints between 5 and 10 random strings of letters (between “a” and “z”), one per line. Each string should have random length of up to 80 characters.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

package indefinite_loops;

import java.util.Random;

public class RandomAlphabets {

	public void randomLines() {

		Random random = new Random();
		String alphabets = "abcdefghijklmnopqrstuvwxyz";
		// since argument is exclusive, add 1;
		int numOfLines = random.nextInt(5 + 1) + 5;

		// for loop to print number of lines
		for (int i = 0; i < numOfLines; i++) {

			int numOfCharacters = random.nextInt(80);
			// for loop to print characters in each line
			for (int j = 0; j < numOfCharacters; j++) {

				int RandomCharacterIndex = random.nextInt(26);
				char character = alphabets.charAt(RandomCharacterIndex);
				System.out.print(character);

			}
			System.out.println();

		}

	}

	public static void main(String args[]) {

		// call the method
		new RandomAlphabets().randomLines();

	}

}
Output:

uzleduruixvsjzjapslfthitsnpfowapwqwqa
efzgguufwncbrbbyjpeactsxsffwmxkefqidhijvxljle
vummwuiztvfqewfgdwtgiijxgoyvtnorpytgevhwlwxiohvypspnqlnwkcfbcomx
lqznqkbswkqjgmikz
lfryufgzvbhehbxwhyukwkqkvutltoydihfav
gfbtkmtliegse
srgphammsxyvunwdpxalvcanbatrcciqztwwywmpgcpbruqanhzvdpduouknhqsowprfclajj

 

0 0

Discussions

Post the discussion to improve the above solution.