我是程序员爱好者,已经学习Java大约一个月了。所以,我决定通过r / dailyprogramming来解决问题。对于那些感兴趣的人,链接如下:
http://www.reddit.com/r/dailyprogrammer/comments/2nynip/2014121_challenge_191_easy_word_counting/
到目前为止,我已经将这些单词拆分为一个名为splitted的String数组。所有单词都被降低了句号,句号,逗号和其他一些常见的标点符号,导致数组中填充了小写字母。目前,我试图通过获取非空的数组的第一个单词来计算每个单词的出现次数,然后检查每个单元并计算每个出现的次数。我使用嵌套for循环和if语句来完成此任务。但是,程序会突然停止而不会返回任何错误。我希望有人可以向我解释为什么我的代码会突然停止。
在这部分代码之前,一切正常。
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;
}
}
这是修改后的代码,其输出位于不同的点。我检查了数组长度,但它没有超出界限。
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(j + " is less than " + splitted.length);
}
System.out.println(word + ": " + count);
count = 0;
}
System.out.println(splitted[i] + " " + i);
}
编辑更清晰:问题是程序在检查数组中的null元素后突然停止,尽管j小于splitted.length。
输出:
Today was great hello stupid Today. Today was bad. Today was amazing. He is great. He was bad. Now he is great!
Word is: today
0 today TRUE
0 is less than 22
1 was FALSE
1 is less than 22
2 great FALSE
2 is less than 22
3 hello FALSE
3 is less than 22
4 stupid FALSE
4 is less than 22
5 today TRUE
5 is less than 22
6 today TRUE
6 is less than 22
7 was FALSE
7 is less than 22
8 bad FALSE
8 is less than 22
9 today TRUE
9 is less than 22
10 was FALSE
10 is less than 22
11 amazing FALSE
11 is less than 22
12 he FALSE
12 is less than 22
13 is FALSE
13 is less than 22
14 great FALSE
14 is less than 22
15 he FALSE
15 is less than 22
16 was FALSE
16 is less than 22
17 bad FALSE
17 is less than 22
18 now FALSE
18 is less than 22
19 he FALSE
19 is less than 22
20 is FALSE
20 is less than 22
21 great FALSE
21 is less than 22
today: 4
null 0
Word is: was
1 was TRUE
1 is less than 22
2 great FALSE
2 is less than 22
3 hello FALSE
3 is less than 22
4 stupid FALSE
4 is less than 22
谢谢,
答案 0 :(得分:0)
问题是您没有在第二个null
循环中检查for
:
for (int j = i; j < splitted.length; j++) {
if (splitted[j].contains(word)) {//what if splitted[j] is null?
splitted[j] = null;
count++;
}
}
如果遇到null
,例如因为早期的迭代已将项目设置为null
,则会获得NullPointerException
。
所以你应该使用:
for (int j = i; j < splitted.length; j++) {
if (splitted[j] != null && splitted[j].contains(word)) {//what if splitted[j] is null?
splitted[j] = null;
count++;
}
}
但是,此代码还有其他一些方面并不完全正确:
equals
而不是包含,因为"foobarqux".contains("bar")
是true
。HashMap<String,Integer>
来计算实例来更有效地(在 O(n log n))时间内完成此操作。选中jdoodle。