简体   繁体   中英

Randomly choose a word from a text document

I have a method called getWord() and I don't know what to add to it to actually choose a word from a text file. My text file consists of 5 words. Its easy printing all words in document, but how can I print one word differently each time I run the program. My code is below.

private Scanner file;
private final List<String> words;

public TextFile(){
    words = readFile();
}

public String getWord(){

return numOfWords;

}

private List<String> readFile() {

    List<String> wordList = new ArrayList<String>();

    try {
        file = new Scanner(new File("words.txt"));

        }

    } catch (FileNotFoundException e) {
        System.out.println("File Not Found");
    } catch (Exception e) {
        System.out.println("IOEXCEPTION");
    }

    return wordList;
}

public static void main(String[] args) {

    TextFile file = new TextFile();
}

If you already have a list of the words in the text file, it looks like your question boils down to how to choose a random number for the index of the word to print. There are two ways to do this in Java (as far as I know).

You can use a Random object.

List<String> words;    // assign stuff to words
Random r = new Random();

//yields random number in the range of 0 to words.size()-1 inclusive
int num = r.nextInt(words.size());

Or you can use Math.random() . Math.random() returns a double between 0 (inclusive) and 1 (exclusive).

List<String> words;    // assign stuff to words
int index = (int)(Math.random() * words.size());

There's also the version where your file is 100GB, but you have a word iterator:

Iterator<String> iterator = ...;
long wordNumber = 0;
String word = null;
while (iterator.hasNext()) {
    String nextWord = iterator.next();
    if (Math.random() < 1.0 / ++wordNumber) {
        word = nextWord;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM