I am examining the JAVA solution @: https://www.chegg.com/homework-help/java-how
ID: 3774475 • Letter: I
Question
I am examining the JAVA solution @:
https://www.chegg.com/homework-help/java-how-to-program-late-objects-10th-edition-chapter-14-problem-5e-solution-9780132575652
I need to know how to:
Create a Word class that contains the four-word arrays and set the values of the arrays in the constructor for the class.
Also create an instance variable of type Random to be used by the getters to come up with the random words.
Create getters (getArticle(), getNoun(), etc.) that use the random number generator to randomly select a word and return it to the calling client.
Create a Sentence class that uses the Word class (declare an instance variable of type Word) to build sentences.
Create a method called getSentence() that builds a sentence and returns that sentence as a String to the calling client.
The driver program (the class that contains main()) should create a Sentence object and call its getSentence() function 20 times (use a for loop) printing out the results of each call.
Explanation / Answer
import java.util.Random;
class Word{
String[] word = new String[]{"one", "two", "three","four"};
String getWord(int x)
{
return word[x];
}
}
class Sentence{
Word a=new Word();
Random random = new Random();
String sentence;
String getSentence(){
sentence = "";
for(int i=0;i<5;i++)
{int x=random.nextInt(4);
String random_word=a.getWord(x);
sentence=sentence+" "+random_word;
}
return sentence;
}
}
public class Program {
public static void main(String[] args) {
Sentence s=new Sentence();
for(int i=0;i<20;i++)
{System.out.println(s.getSentence()); //Prints 20 sentences with each sentence having five words
}}}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.