Question: We can create a method to pick a random word from the words.txt file. The basic idea for this method is to a) find the

We can create a method to pick a random word from the words.txt file. The basic idea for this method is to

a) find the number of words in the file using countWords (countWords is another method)

b) generate a random number N between 0 and the number of words

c) (loop) read N words from the file into a word variable.

d) return the value stored in word

Since every word read from the file and stored in variable word replaces the last, when the loop is finished, the value stored in word will be the Nth word in the file, where N is a random number that will be different every time the program is run.

So now we will write a randomWord method that takes a fileName parameter and returns a word chosen at random from the file. Change the header for randomWord so it returns a String word, the random word selected from the file. Then, modify the loop in randomWord so instead of reading the whole file it only reads N words from the file. Finally, modify the return statement in randomWord so it returns word instead of count.

so far my code for randomWord method is this...

public static String randomWord(String fileName) throws FileNotFoundException { // find the number of words in fileName and store in variable fileSize int fileSize = countWords("words.txt"); // generate a random number between 0 and fileSize int N = (int)(fileSize*Math.random()); Scanner inFile = new Scanner(new File(fileName)); String word; int count = 0; while(inFile.hasNext()){ word = infile.next(); count ++; } return word; }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!