首页 > 解决方案 > 随机词生成器,我想限制它从 .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);

标签: java

解决方案


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)


推荐阅读