java - 计算单词中字母的偶数和奇数

标签 java for-loop if-statement

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

    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);
}

我想我做错的是我没有访问文本文件的正确部分。我确实有一个获取我想要的信息的函数,它是 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-condition 进行比较:

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());

您可以完全按照其他代码示例中所示使用此。或者,您不需要将所有内容都收集到一个新列表中,您可以直接留在 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)

关于java - 计算单词中字母的偶数和奇数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47685492/

相关文章:

python - 读取 CSV 文件并在没有特定行的情况下重写它们 Python

javascript - 永无止境的for循环javascript

android - Kotlin:将 'cascade if' 替换为 'when' 与其他变量进行比较

java - 使用 Java 对数百万个 int/string 对进行排序

java - 具有求和功能的 For 循环

java - 如何处理/URL,同时对/js、/css进行默认处理,

javascript - If then 琐事陈述

c - If 语句检查 argv 是否为数字

java - android.os.Bundle 无法在 libgdx Android 项目中解析

java - 更新 ArrayList<HashMap<String 到 ListView (未定义的 simpleadapter 错误)