lundi 12 janvier 2015

Java Nested For Loop Breaking Abruptly

I'm a programmer ethusiasts and have been learning Java for about a month now. So, I decided to take on a problem offered through r/dailyprogramming. The link is below for those that are interested:


http://ift.tt/1yw2s1I


So far I have splitted the words into a String array called splitted. The words are all lowered cased and periods, commas, and some other common punctuation, resulting in an array filled with lowercase lettered words. Currently I'm trying to count the number of occurence of each word by taking in the first word of the array that is not null and then checking each element and counting for each occurences. I used nested for loops and if statements to accomplish this. However, the program keeps abruptly stopping without returning any errors. I'm hoping someone can explain to me why my code is abruptly stopping.


Everything works fine until this part of the code.



for (int i = 0; i < splitted.length; i++)
{
if (splitted[i] != null)
{
word = splitted[i];
System.out.println("Word is: " + word);

for (int j = i; j < splitted.length; j++)
{
if (splitted[j].contains(word))

{
splitted[j] = null;
count++;
}
}
System.out.println(word + ": " + count);
count = 0;
}
}


This is the modified code with outputs at different points. I have checked for the array length and it is not out of bound.



for (int i = 0; i < splitted.length; i++)
{
if (splitted[i] != null)
{
word = splitted[i];
System.out.println("Word is: " + word);

for (int j = i; j < splitted.length; j++)
{
System.out.printf("%d %s %B%n", j, splitted[j], splitted[j].contains(word));
if (splitted[j].contains(word))

{
splitted[j] = null;
count++;
}
}
System.out.println(word + ": " + count);
count = 0;
}
System.out.println(splitted[i] + " " + i);
}


Thanks,


Aucun commentaire:

Enregistrer un commentaire