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

时间:2015-10-27 03:13:05

标签: java

我有一个文本文件rext.txt,我试图从文本的每一行获得前100个随机单词 文件并将它们放入String数组中,但它不起作用。我想到了如何从文本中分离文件 并将它们放入数组中,但我无法确定在哪里包含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);


        }
}
}

1 个答案:

答案 0 :(得分:1)

首先,从文件中获取100个单词。然后随机化数组。

res/layout

然后您可以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; } } } 并显示shuffle

words