【问题标题】:Removing Puncuation Marks off a text file and then calculating odd and even length words从文本文件中删除标点符号,然后计算奇数和偶数长度的单词
【发布时间】:2016-12-06 01:45:09
【问题描述】:

到目前为止,我已经在代码中做了很多工作。我从文本文件中替换了标点符号,但我不知道如何找到偶数和奇数长度的单词并将它们添加到它们的计数中。所以:我的这个文件的字数是 114 个字,但是这个程序返回 50 个偶数字和 55 个奇数字,这与我的 114 个字数不相加,所以显然有问题。

【问题讨论】:

  • 我认为您应该将 System.out.println 语句放在 while 循环中,以在每行之后显示计数。您可能还需要发布文件的内容,因为没有它就很难解决这个问题..

标签: java arrays arraylist bufferedreader


【解决方案1】:
       BufferedReader file3 = new BufferedReader(new FileReader("sonnet1-b.txt"));

        int even = 0;
        int odd = 0;
        String lines;
        String processedLine = "";

//这个变量以后会不会有更大的用途还不清楚

        ArrayList<String> words = new ArrayList<>();

        while ((lines = file3.readLine()) != null) {
            processedLine = lines.replaceAll("'", "").replaceAll("[^a-zA-Z]", " ").replaceAll("( )+", " ");

//我这里去掉了单词,把split改成在空格上split。当我运行您的原始代码时,整个文本作为一行出现。我认为您最初的问题可能出在这个领域。你需要得到单词的长度。你原来的分割参数只在每个参数中放了空格。

            String[] each = processedLine.split(" ");
            for (String str1 : each) {

//根据你的描述,你需要检查str1的长度,而不是每个。

                if (!(str1.length() % 2 == 0)) {
                    odd++;
                } else {
                    even++;
                }
            }
        }                               
        System.out.println("There were " + even + " even words, and " + odd + " odd words"); 

偶数58个,奇数56个

【讨论】:

  • 很难理解您认为第二个文本的问题所在。我怀疑输出的字数比您预期的要多。问题可能是没有尽头的世界被算作 3 个单词。所以... processedLine = lines.replaceAll("'", "").replaceAll("-","").replaceAll("[^a-zA-Z]", " ").replaceAll("( ) +", "");
猜你喜欢
  • 2019-04-26
  • 2020-08-28
  • 2013-02-15
  • 2014-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多