簡體   English   中英

從文本文檔中隨機選擇一個單詞

[英]Randomly choose a word from a text document

我有一個名為getWord()的方法,但我不知道要從文本文件中實際選擇一個單詞來添加什么內容。 我的文本文件包含5個字。 它很容易打印文檔中的所有單詞,但是每次運行程序時如何以不同的方式打印一個單詞。 我的代碼如下。

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();
}

如果文本文件中已經有單詞列表,則您的問題似乎歸結為如何為打印的單詞索引選擇隨機數。 在Java中,有兩種方法可以做到這一點(據我所知)。

您可以使用Random對象。

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());

或者,您可以使用Math.random() Math.random()返回介於0(含)和1( Math.random()之間的雙Math.random()值。

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

還有一個版本,文件大小為100GB,但是有一個單詞迭代器:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM