ccless1 ccless1 - 1 month ago 18
Java Question

How to select a random word from a txt file?

I have a method that needs to select a random word from a txt file, but it only works some of the time.

The content of the file is as follows:

Broccoli
Tomato
Kiwi
Kale
Tomatillo


My code:

import java.util.Random;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public String getRandomItem(){
Scanner fileIn = null;

String temp = "";
int r = randomGenerator.nextInt(5) + 1;
byte i = 0;

try {
fileIn = new Scanner(new FileInputStream("bundles.txt"));
} catch (FileNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}

while(i <= 5){
temp = fileIn.nextLine();

if(i == r){
break;
}

i++;
}

fileIn.close();

return temp;
}


Could someone please tell me where I am going wrong?

Answer

I would use Files.readAllLines(Path) to read all the lines once, and then get a single random word from that. Something like,

private static List<String> lines = null;
static {
    try {
        lines = Files.readAllLines(new File("bundles.txt").toPath());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
private Random rand = new Random();

public String getRandomItem() {
    return lines.get(rand.nextInt(lines.size()));
}