我是一名程序员爱好者,并且一直在学习Java大约一个月。所以,我决定接受通过r/dailyprogramming提供的问题。链接下面是对于那些有兴趣:Java嵌套For-loop突然崩溃
http://www.reddit.com/r/dailyprogrammer/comments/2nynip/2014121_challenge_191_easy_word_counting/
到目前为止,我已经分裂的话到名为分裂的字符串数组。这些单词全部被降低了下来,句点,逗号和其他一些常见的标点符号,导致数组填充了小写字母词。目前我试图通过取数组中的第一个非空的单词来计算每个单词的出现次数,然后检查每个单元并计算每个单词的出现次数。我使用嵌套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);
}
被修改为更清晰:问题是检查阵列中的一个空元素之后,突然停止尽管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
感谢,
你能显示你的输出吗?你认为什么导致你的代码停止? –
如果splitted [j]设置为null(发生在您的代码中),则splitted [j] .contains(word)将停止在空指针异常处,下一次遇到split [j]时。 – user2533521
语法警察:“分裂”是一个不规则的动词,简单的过去和过去分词也是“分裂”(而不是“分裂”):) – xpa1492