怎么知道生成的是有效的单词的
时间: 2024-02-25 07:52:31 浏览: 33
要保证生成的单词是有效的单词,需要借助一个词典或者字典库。在 Java 中可以使用 Apache Commons Text 库中的 `WordUtils` 类来判断一个单词是否在字典中存在。以下是一个示例代码:
```java
import org.apache.commons.text.WordUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
public class RandomWordGenerator {
private static final String LETTERS = "abcdefghijklmnopqrstuvwxyz";
private static final Random RANDOM = new Random();
private static final Set<String> DICTIONARY = loadDictionary();
private static Set<String> loadDictionary() {
// 从文件中加载字典
Set<String> dictionary = new HashSet<>();
try {
List<String> lines = Files.readAllLines(new File("dictionary.txt").toPath());
for (String line : lines) {
dictionary.add(line.toLowerCase());
}
} catch (IOException e) {
e.printStackTrace();
}
return dictionary;
}
public static String generate(int length) {
String word;
do {
// 不断生成随机单词,直到生成的单词在字典中存在
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
int index = RANDOM.nextInt(LETTERS.length());
sb.append(LETTERS.charAt(index));
}
word = sb.toString();
} while (!WordUtils.isWord(word, DICTIONARY));
return word;
}
public static void main(String[] args) {
// 生成长度为 5 的随机单词
String word = generate(5);
System.out.println(word);
}
}
```
在这个代码中,我们从一个文本文件中加载了一个字典,然后在生成随机单词时,不断生成随机单词,直到生成的单词在字典中存在。这样可以确保生成的单词都是有效的单词。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)