Java从dictionary.txt文件中获取100个随机单词

Java从dictionary.txt文件中获取100个随机单词,java,Java,我有一个文本文件rext.txt,我正试图从每行文本中获取前100个随机单词 文件并将它们放入字符串数组中,但它不起作用。我想到了如何将文件和文本分开 并将它们放入数组中,但我不知道在何处包含100以对它们进行排序。 谢谢你 import java.io.File; import java.io.FileNotFoundException; import java.util.Random; import java.util.Scanner; public class New2 {

我有一个文本文件rext.txt,我正试图从每行文本中获取前100个随机单词 文件并将它们放入字符串数组中,但它不起作用。我想到了如何将文件和文本分开 并将它们放入数组中,但我不知道在何处包含100以对它们进行排序。 谢谢你

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

public class New2 
    {
     public static void main(String[] args) throws FileNotFoundException 
        {
         Scanner sc = new Scanner(new File("dictionary.txt"));
         while (sc.hasNext())   
             {
             String word = sc.next();
             sc.nextLine();   
             String[] wordArray = word.split(" "); 
             //System.out.println(Arrays.toString(wordArray));
             int idx = new Random().nextInt(wordArray.length);
             String random = (wordArray[idx]);
             System.out.println(random);


        }
}
}

首先,从文件中找出你的100个单词。然后随机化数组

String[] words = new String[100];
int pos = 0;
Scanner sc = new Scanner(new File("dictionary.txt"));
while (sc.hasNextLine() && pos < words.length) {
    String line = sc.nextLine();
    String[] wordArray = line.split("\\s+"); // <-- one or more consecutive 
                         //  white space characters.
    for (String word : wordArray) {
        words[pos] = word;
        pos++;
        if (pos >= words.length) {
            break;
        }
    }
}

输出看起来不正确。它只是混合了大量的空值和文本。
Collections.shuffle(Arrays.asList(words));
System.out.println(Arrays.toString(words));