我目前正在尝试计算一个文本文件中有多少个单词具有偶数和奇数个字符,但我似乎无法使其正常工作。到目前为止,我已经完成了

    int countEven = 0;
    int countOdd = 0;
    for (int i = 0; i <latinLength.length(); i++) {
        if (Character.isLetter(latinLength.charAt(i))) {
            countEven++;
        } else {
            countOdd++;
        }
    }
    System.out.println("Total number of unique even words in Latin names = " + countEven);
    System.out.println("Total number of unique odd words in Latin names = " + countOdd);
}


我认为我做错了什么是我没有访问文本文件的正确部分。我确实有一个我想要的信息的get函数,即getLatinName,但是我不确定如何正确实现它

    String tempLatinName = " ";
    String latinLength = " ";
    int letters = 0;
    for (int i = 0; i < info.size(); i++) {
        tempLatinName = info.get(i).getLatinName();
        latinLength = tempLatinName.replace(" ","");
        letters += latinLength.length();
    }
    System.out.println("Total number of letters in all Latin names = " + letters);


我已经编辑了代码以显示我在尝试计算多少个单词具有奇数和偶数个字符之前所做的工作,上面的代码是计算每个单词的总字符数,然后给我总计

/**
*
* @author g_ama
*/
import java.io.*;
import java.util.*;

public class Task1 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws FileNotFoundException, IOException {

    BufferedReader reader = new BufferedReader(new FileReader("shark-data.txt"));
    String line;
    List<Shark> info = new ArrayList<>();
    while ((line = reader.readLine()) != null) {
        String[] data = line.split(":");

        int MaxLength = Integer.parseInt(data[2]);
        int MaxDepth = Integer.parseInt(data[3]);
        int MaxYoung;
        try {
            MaxYoung = Integer.parseInt(data[4]);
        } catch (Exception X) {
            MaxYoung = -1;
        }
        int GlobalPresence = Integer.parseInt(data[5]);

        ArrayList<String> OceanicRegion = new ArrayList<>();
        String[] Region = data[6].split(",");
        for (String Element : Region) {
            OceanicRegion.add(Element);
        }

        Shark shark = new Shark(data[0], data[1], MaxLength, MaxDepth, MaxYoung, GlobalPresence, OceanicRegion);

        info.add(shark);
    }
    Collections.sort(info);
    System.out.println("The three largest sharks");
    System.out.println(info.get(info.size() - 1).getCommonName() + ", " + info.get(info.size() - 1).MaxLength + " cm");
    System.out.println(info.get(info.size() - 2).getCommonName() + ", " + info.get(info.size() - 2).MaxLength + " cm");
    System.out.println(info.get(info.size() - 3).getCommonName() + ", " + info.get(info.size() - 3).MaxLength + " cm");

    System.out.println("The three smallest sharks");
    System.out.println(info.get(0).getCommonName() + ", " + info.get(0).MaxLength + " cm");
    System.out.println(info.get(1).getCommonName() + ", " + info.get(1).MaxLength + " cm");
    System.out.println(info.get(2).getCommonName() + ", " + info.get(2).MaxLength + " cm");

    //count total characters for Latin Name
    String tempLatinName = " ";
    String latinLength = " ";
    int letters = 0;
    for (int i = 0; i < info.size(); i++) {
        tempLatinName = info.get(i).getLatinName();
        latinLength = tempLatinName.replace(" ", "");
        letters += latinLength.length();
    }
    System.out.println("Total number of letters in all Latin names = " + letters);

    //count even or odd words
    int countEven = 0;
    int countOdd = 0;
    for (int i = 0; i < latinLength.length(); i++) {
        if (Character.isLetter(latinLength.charAt(i))) {
            countEven++;
        } else {
            countOdd++;
        }
    }
    System.out.println("Total number of unique even words in Latin names = " + countEven);
    System.out.println("Total number of unique odd words in Latin names = " + countOdd);
}


}

最佳答案

说明

当前,您只计算文本中有多少个字母和非字母。那当然不是偶数或奇数的数量。

例如,如果您有一个类似

test12foo!$bar


您的代码当前将输出

countEven => 10  // Amount of letters (testfoobar)
countOdd  => 4   // Amount of non-letters (12!$)


将此与您的if条件进行比较:

if (Character.isLetter(latinLength.charAt(i))) {
    countEven++;
} else {
    countOdd++;
}


您想要的是计算单词长度是偶数还是奇数的频率,所以假设像

test     // length 4, even
foo      // length 3, odd
bartest  // length 7, odd


然后你想要

countEven => 1 // (test)
countOdd  => 2 // (foo, bartest)






相反,您将需要将文本拆分为单词(标记)。之后,您将需要为每个单词计算字符数。如果是这样,您可以将countEven增加一。同样,如果countOdd++是一个奇数。

核心将是这种情况

word.length() % 2 == 0


如果单词的长度为偶数,则为true;如果为奇数,则为false。您可以轻松地自己验证(%除法后返回余数,在这种情况下为01)。

假设您的文本结构很简单,单词总是用whitespace分隔,即类似

test foo bar John Doe


总的来说,您的代码可能看起来像

Path path = Paths.get("myFile.txt");
AtomicInteger countEven = new AtomicInteger(0);
AtomicInteger countOdd = new AtomicInteger(0);
Pattern wordPattern = Pattern.compile(" ");

Files.lines(path)                         // Stream<String> lines
    .flatMap(wordPattern::splitAsStream)  // Stream<String> words
    .mapToInt(String::length)             // IntStream length
    .forEach(length -> {
        if (length % 2 == 0) {
            countEven.getAndIncrement();
        } else {
            countOdd.getAndIncrement();
        }
    });


System.out.println("Even words: " + countEven.get());
System.out.println("Odd words: " + countOdd.get());


或没有所有Stream内容:

Path path = Paths.get("myFile.txt");

List<String> lines = Files.readAllLines(path);
List<String> words = new ArrayList<>();

// Read words
for (String line : lines) {
    String[] wordsOfLine = line.split(" ");
    words.addAll(Arrays.asList(wordsOfLine));
}

// Count even and odd words
int countEven = 0;
int countOdd = 0;
for (String word : words) {
    if (word.length() % 2 == 0) {
        countEven++;
    } else {
        countOdd++;
    }
}

System.out.println("Even words: " + countEven);
System.out.println("Odd words: " + countOdd);




调整为您的特定代码

当您刚刚添加了特定的代码后,我将添加一个适合它的解决方案。

在您的代码中,列表info包含所有Shark。在这些鲨鱼中,您要考虑的词由Shark#getLatinName表示。因此,您需要做的只是这种事情:

List<String> words = info.stream()  // Stream<Shark> sharks
    .map(Shark::getLatinName)       // Stream<String> names
    .collect(Collectors.toList());


您可以完全按照其他代码示例所示使用此words。另外,您不需要将所有内容收集到新列表中,可以直接留在Stream并继续前面显示的流方法。总而言之:

AtomicInteger countEven = new AtomicInteger(0);
AtomicInteger countOdd = new AtomicInteger(0);

info.stream()                             // Stream<Shark> sharks
    .map(Shark::getLatinName)             // Stream<String> names
    .mapToInt(String::length)             // IntStream length of names
    .forEach(length -> {
        if (length % 2 == 0) {
            countEven.getAndIncrement();
        } else {
            countOdd.getAndIncrement();
        }
    });

System.out.println("Even words: " + countEven);
System.out.println("Odd words: " + countOdd);


并将其替换为代码中的该部分:

//count even or odd words

(substitute here)

08-03 19:53
查看更多