java - Array is out of bounds while counting [CORRECT] -


i need print array contains duplicate words. have array working cannot figure out how count words properly. know when index counter (i) @ 49, , when (i) wants count 50, error don't know other way adjust method work. can please me? appreciated!

this array:

blue blue blue blue blue blue blue blue blue blue blue blue blue brown green green green green green green green green lemon lemon lemon lemon lemon lemon lilac lilac orange orange red red red red red red red red red red white white white white white yellow yellow yellow

corrected code

public static void printwordcount(string[] z)  {     system.out.println("there " + wordtotal + " words in file");     system.out.println("word w/ count:");      int = 0;     int count = 0;      while(i < z.length - 1) {         if (z[i].equalsignorecase(z[i+1])) {             i++;             count++;         }         else if (!z[i].equalsignorecase(z[i+1]) || == z.length - 1) {             count++;             system.out.println(z[i] + " / " + count);             i++;             count = 0;         }     }     count++;     system.out.println(z[i] + " / " + count); } 

this output:

there 50 words in file

word w/ count:

blue / 13

brown / 1

green / 8

lemon / 6

lilac / 2

orange / 2

red / 10

white / 5

yellow / 3

your condition allows i reach z.length - 1. z[i].equalsignorecase(z[i+1]) brings out of array bounds, since i+1 == z.length.

if wish compare ith elements i+1th element, change condition :

while(i < z.length - 1)  

then should add after loop :

        count++;         system.out.println(z[i] + " / " + count); 

to print number of occurences of final word.


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -