gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:55:23 25 4
gpt4 key购买 nike

我有一个文本文件 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;
}
}
}

然后你可以随机播放并显示words like

Collections.shuffle(Arrays.asList(words));
System.out.println(Arrays.toString(words));

关于Java 从 dictionary.txt 文件中获取 100 个随机单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33359340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com