如何在给定文件和记录中长度大于3的单词数

问题描述 投票:-3回答:2

我正在尝试搜索给定的文本文档。对于长度为3或更长的单词,然后记录每个单词的数量并在屏幕上显示。我会把我到目前为止的内容放在下面。我在查找文档中单词的最大长度时遇到了问题。所以我知道什么时候停止录音。另外,我在修改程序时遇到了麻烦,而不是运行那么多if if语句。

问候!

public static int WordLengthCount() throws FileNotFoundException {
File file = new File("document.txt");
Scanner keyboard = new Scanner(new FileInputStream(file));
    int count5 = 0;
    int count6 = 0;
    while (keyboard.hasNext()) {
        if (keyboard.next().length() == 5) {
            count5++;
        }
        else if (keyboard.next().length() == 6) {
            count6++;
}

}
return count5;
java
2个回答
0
投票

你在.next()循环中调用while两次,所以你实际上在每次迭代时读取2个字符串,而不是一个。您需要将.next()返回的String存储在变量中,并检查该字符串的长度。您的第一个if语句正在读取文件中的下一个String并检查其长度,并且else if正在读取前一个String之后的String并检查其长度。

while (keyboard.hasNext()) {
    final String next = keyboard.next();
    if (next.length() == 5) {
        count5++;
    } else if (next.length() == 6) {
        count6++;
    }
}

如果您需要计算的字符数是动态的,则可以使用Map

final Map<Integer, Integer> charCount = new HashMap<>();
//the key for this map is the length of the word and the value is the number of times a word with that length was found
while (keyboard.hasNext()) {
    final String next = keyboard.next();
    final Integer len = next.length();
    if(charCount.has(len){
       charCount.put(len, charCount.get(len)+1);
    } else {
       charCount.put(len, 1);
    }
}
//print the values
for(final Integer key: charCount.keySet()){
    System.out.println("A word with length " + key + " characters was found "+ charCount.get(key) + " times.");
}

0
投票

如果您使用的是Java 8或更高版本,那么此解决方案可以帮助您。

  • 使用Map来保存每个长度的计数器(值)(键)
  • 对于长度> = 3的任何单词,我使用merge来创建/更新计数器的长度
  • 使用流对键进行排序,并按升序打印长度和计数
  • 使用stream和max方法找到键的最大值,这是最长的单词

public static int wordLengthCount() throws FileNotFoundException {
    File file = new File("document.txt");
    Scanner keyboard = new Scanner(new FileInputStream(file));
    Map<Integer, Integer> wordLengths = new HashMap<>();
    while (keyboard.hasNext()) {
        String word = keyboard.next();
        Integer length = word.length();
        if (length >= 3) {
            wordLengths.merge(length, 1, Integer::sum);
        }
    }
    keyboard.close();

    wordLengths.keySet().stream().sorted(Comparator.naturalOrder()).forEach(key -> {
        System.out.printf("Word length %d occured %d times\n", key, wordLengths.get(key));
    });

    int maxLength = wordLengths.keySet().stream().max(Comparator.naturalOrder()).get();
    return maxLength;
}

public static void main(String[] args) throws Exception {
    System.out.println("Max length = " + wordLengthCount());
}
© www.soinside.com 2019 - 2024. All rights reserved.