java - 随机词生成器,我想限制它从 .txt 文件中读取的词的大小,最多说 3 个字符
问题描述
// 随机单词生成器,我想限制单词的大小 // 它从 .txt 文件中读取最多 3 个字符,而不使用 // 仅返回 System.Out.Print
public void RandomWordGenerator() {
List<String> words = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader("dictionary.txt"))) {
String word;
while ((word = reader.readLine()) != null) {
words.add(word);
}
} catch (IOException e) {
System.out.println("Unable to find file");
}
Random random = new Random();
String randomWord = words.get(random.nextInt(words.size()));
System.out.println(randomWord);
解决方案
you can just use length field of the string to get it's length
String word;
while ((word = reader.readLine()) != null) {
if (word.trim().length <= MAX_LENGTH) {
words.add(word);
}
}
Where MAX_LENGTH is constant that contains the max length (in this case MAX_LENGTH = 3)
推荐阅读
- python - Pygame - 检测矩形的哪一侧与另一侧的哪一侧碰撞
- git - 连接到存储库时出现 Jenkins-Git 集成问题
- react-native - 使用 redux-observable 每秒调度一个动作
- python - 如何使用串行波特率 115200 而不是 9600 使用 python 脚本启动 telnet
- git - Git命令获取我已更改的行的作者
- swift - NotificationCenter 处理程序更新变量但 UILabel 保持不变
- react-native - 在反应原生中单击按钮后如何导航到其他页面?
- java - Spring中的JSR 303验证-当字段应该只接受整数时如何拒绝数字字符串
- python - 我在理解如何正确使用 pandas 旋转数据框时遇到问题
- javascript - 是否可以通过按类名定位列表容器来附加列表项?