[英]Java get 100 random words from dictionary.txt file
我有一个文本文件 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);
}
}
}
首先,从文件中获取 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;
}
}
}
然后你就可以shuffle
和显示words
喜欢
Collections.shuffle(Arrays.asList(words));
System.out.println(Arrays.toString(words));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.