程序不会增加循环变量

时间:2017-12-06 17:37:41

标签: java string loops

对于我的程序,我试图找出数据文件中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

2 个答案:

答案 0 :(得分:3)

你没有正确处理你的单词:你在计算三个单词的句子,其中你有零,而不是三个字母的单词。你需要另一个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.

答案 1 :(得分: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;
    }
}