2017-12-06 7 views
1

私のプログラムでは、データファイル内の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 

これは、プログラムがwordCount

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 
+0

は[整数の除算の重複のようになります。どのようにダブルを生成するのですか?](https://stackoverflow.com/q/2909451/5475891)、その問題はあなたの問題を解決するはずです – phflack

+0

例外メッセージを分析してください。コード行などの正確な情報があります。デバッガを使用します。 SOはデバッグサービスではありません –

+1

@JacekCz質問を読んでも例外はありません。問題は 'smallerInt/biggerInt = 0.0'です。 – phflack

答えて

3

あなたが正しくあなたの言葉を処理していない:あなたは、ゼロを持っている3つのワードの文章、ではなく、3文字の単語を数えています。正しく

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

また、あなたが計算されていない割合:あなたは別のforここでループを必要とするthreeLettersは分子、分母ではないはずです。

最後に、あなたは、全体の数字にパーセントを切り捨て、あなたのカウンタのdoubleを使用するか、分割前にそれらをキャストしたい場合を除き:

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

Demo.

2

あなたが分割していないから読んでいるテキストファイル、あなたはthreeLettersで割るいるです。何もそれを増やしていないので、それは確かに0です。

あなたのロジックに問題がここにある:

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

あなたは言葉はどのように長く数えていない、あなたは多く言葉がに並ぶにあるかをカウントしています。そしてそのファイルの行には正確に3語しかないので、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; 
    } 
} 
関連する問題