Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Below is a method that picks a random word from the library for the game of hang

ID: 3739757 • Letter: B

Question

Below is a method that picks a random word from the library for the game of hangman. How can I call that word in other methods? How can I print/return that word to see it on the console. What exactly is the method doing step-by-step? Your help is greatly appreciated.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;

public class Hangman {

final static int nWords = 2266;

/**
* Do NOT modify this method This method chooses a word from a text file
* randomly.
*
* @param f
* @return
* @throws FileNotFoundException
*/
public static String chooseWord(File f, Random r) throws FileNotFoundException {
Scanner fileIn = new Scanner(f);
try {
int randInt = r.nextInt(nWords);
int i = 0;
while (i != randInt) {
fileIn.nextLine();
i++;
}
return fileIn.nextLine();
} catch (Exception e) {
return "";
} finally {
fileIn.close();
}
  
}

Explanation / Answer

import java.io.File;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.util.Random;

import java.util.Scanner;

public class Hangman {

final static int nWords = 2266;

/**

* Do NOT modify this method This method chooses a word from a text file

* randomly.

*

* @param f

* @return

* @throws FileNotFoundException

*/

public static String chooseWord(File f, Random r) throws FileNotFoundException {

Scanner fileIn = new Scanner(f);

try {

int randInt = r.nextInt(nWords); //Here we will get the random number below the given number of words

int i = 0;

while (i != randInt) { //This is for iteration upto the random number

fileIn.nextLine(); // For each iteration the words will be read from the file

i++; // i th increment

}

return fileIn.nextLine(); //when the variable i equals to random number loop will terminate and the current line/word will be return by the method

} catch (Exception e) {

return ""; // if any exception caught this method return the empty string value

} finally {

fileIn.close(); // after end of the process we have to close the file object stream

}

}

public static void main(String args[])throws FileNotFoundException

{

Random r=new Random();

File f=new File("hangmandata.txt"); //Here we are accessing the data file

System.out.println(chooseWord(f,r)); // calling the method which returns the String value.

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote