【问题标题】:Program not increasing variable in loop程序不会在循环中增加变量
【发布时间】:2017-12-06 17:37:40
【问题描述】:

对于我的程序,我试图找出我的数据文件中长度为 3 个字母的单词的百分比。尽管每当我运行程序时,我都会收到一条错误消息,指出您不能除以 0。每次循环运行时,我都会将变量 wordCount 增加 1,但由于某种原因,我的程序将其识别为 0。任何人都可以帮助我我是如何收到这个错误的?

int threeLetters=0;
        int wordCount=0;


        while(inFile.hasNextLine()){
            wordCount= wordCount +1;
            String line = inFile.nextLine();
            String[] word =line.split(" ");
            int wordLength = word.length;
            if (wordLength == 3){
                threeLetters= threeLetters+1;
            }

}
double percentage = wordCount/threeLetters;// error recieved here

这是程序正在读取的文本文件

Good morning life and all
Things glad and beautiful
My pockets nothing hold
But he that owns the gold
The sun is my great friend
His spending has no end
Hail to the morning sky
Which bright clouds measure high
Hail to you birds whose throats
Would number leaves by notes
Hail to you shady bowers
And you green fields of flowers
Hail to you women fair
That make a show so rare
In cloth as white as milk
Be it calico or silk
Good morning life and all
Things glad and beautiful

【问题讨论】:

  • 看起来像 Integer division: How do you produce a double? 的副本,这个问题应该可以解决您的问题
  • 分析异常信息。有哪些代码行等的确切信息。使用调试器。 SO 不是调试服务
  • @JacekCz 如果您阅读了这个问题,也不例外。问题是smallerInt / biggerInt = 0.0
  • @phflack "我收到一条错误消息,指出您不能除以 0" 对我来说确实是个例外。
  • @lyah 但是,第一条评论中的链接是相关的,因为这将是您修复其他内容后的下一个问题。

标签: java string loops


【解决方案1】:

您没有正确处理您的单词:您正在计算三个单词的句子,其中您有零个,而不是三个字母的单词。你需要另一个for 循环:

while(inFile.hasNextLine()){
    String line = inFile.nextLine();
    for (String word : line.split(" ")) {
        wordCount++;
        int wordLength = word.length();
        if (wordLength == 3){
            threeLetters++;
        }
    }
}

此外,您没有正确计算百分比:threeLetters 应该是分子,而不是分母。

最后,除非您想将百分比截断为整数,否则请使用double 作为计数器,或在除法之前强制转换:

double percentage = ((double)threeLetters)/wordCount;

Demo.

【讨论】:

    【解决方案2】:

    您不是除以wordCount,而是除以threeLetters。它确实是 0,因为没有任何东西增加它。

    你的逻辑有问题:

    String[] word =line.split(" ");
    int wordLength = word.length;
    if (wordLength == 3){
        threeLetters= threeLetters+1;
    }
    

    您不是在计算单词的长度,而是在计算 该行 上有多少个 个单词。由于该文件中没有一行恰好包含三个单词,if 永远不会为真,threeLetters 永远不会增加。所以它仍然是 0。

    您需要的是对该数组的另一个循环。像这样的:

    String[] words = line.split(" ");
    for (int i = 0; i < words.length; i++) {
        int wordLength = words[i].length();
        if (wordLength == 3){
            threeLetters = threeLetters + 1;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-07
      • 2015-11-28
      • 2014-11-11
      • 2020-05-26
      • 2013-01-16
      • 2013-11-25
      • 2020-06-11
      • 1970-01-01
      相关资源
      最近更新 更多