(java) Your initial post should be a maximum of two paragraphs and should have a
ID: 3759524 • Letter: #
Question
(java) Your initial post should be a maximum of two paragraphs and should have a series of steps that represents an algorithm. Using pseudocode, write an algorithm. The algorithm will result in a message that is created from five words. The algorithm will first create five Arrays. Each Array stores a list of words. The algorithm will generate a random number that will be used as an index into each Array. The algorithm will use this index to select one word from each of the five Arrays to form a message
Explanation / Answer
1. First of all we will create five arrays and intialize them and since these arrays contain words (strings), we will be using string arrays as
Lets name these five arays w1,w2,w3,w4 anmd w5
String[] w1 = {"Hello", "How ", "Apple", "Fruits", "Animal"}; // The size of the array can be changed as per need
String[] w2 = {"Hello", "How ", "Apple", "Fruits", "Animal"};
String[] w3 = {"Hello", "How ", "Apple", "Fruits", "Animal"};
String[] w4 = {"Hello", "How ", "Apple", "Fruits", "Animal"};
String[] w5 = {"Hello", "How ", "Apple", "Fruits", "Animal"};
2. Net step is to generate a message from these five arrays by fetching one random word from each array. So we will use Java's Math.random() method to obtain a random no. as index as shown below
Random random = new Random();
r = random.nextInt(5); // Since the size of array is 5 we need random number between 0 and 4
3. Next step is to generate a message by fetching one word from each five arrays and to do so generate five random numbers between the range 0 and 4 (including 0 and 4) and then fetch a word from each array as shown in the code below
String message; // This will hold our message
int r; // This will hold the random number generated and will be used as array index
Random random = new Random();
r = random.nextInt(5);
message+= w1[r];
r = random.nextInt(5);
message+= w2[r];
r = random.nextInt(5);
message+= w3[r];
r = random.nextInt(5);
message+= w4[r];
r = random.nextInt(5);
message+= w5[r];
// Display the message
System.out.println(message);
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.