I am trying to make a class for generating random words. So far my choices are Scanner or a BufferReader I am guessing.
This is the code that I think is most efficient however when I run I get null.
Also will a public return randomWord getter grant access to the word in main class?
private static final String filepath = "/assets/words.txt";
public String randomWord;
public Random rand;
private ArrayList<String> words = new ArrayList<String>();
public void WordGenerator() {
rand = new Random();
String line;
try {
InputStream WordsFile = getClass().getResourceAsStream(filepath);
BufferedReader br = new BufferedReader(new InputStreamReader(WordsFile));
if(!br.ready()){
System.out.println("No File");
}
else while ((line = br.readLine()) != null) {
words.add(line);
}
br.close();
}
catch (IOException e) {
System.out.println("Something is wrong");
}
int size = words.size();
Random rn = new Random();
int randWord = rn.nextInt(size);
randomWord = words.get(randWord);
System.out.println(randomWord);
}
}
words.txtfile is not empty?