【发布时间】:2018-08-23 21:46:54
【问题描述】:
我试图通过将句子分成单个单词来制作单词计数器。我尝试通过使用 split 方法(对于对象字符串)来完成此操作。但是,我无法计算单词,因为循环在中途终止。你能帮帮我吗?
Desired: 找出字符串中的单词重复了多少次。
public static void main(String[] args) {
int count = 0, i=0;
int max,a;
ArrayList<Integer> lastCount = new ArrayList<Integer>();
String yazi ="How ı can do that? I don't know. Can you help me? I need help for counter. Thanks in advance for all.";
String yazi1 = yazi.replace(",","");
yazi1 = yazi1.replace(".", "");
yazi1 = yazi1.replace("?", "");
yazi1 = yazi1.replace("!", "");
yazi1 = yazi1.toLowerCase();
yazi1 = yazi1.replace("ı", "i");
String[] words = yazi1.split(" ");
for(a=0; a < words.length; a++) {
while(i<words.length){
if(words[a].equals(words[i])) {
max = 0;
lastCount.add(a, max+1);
}
i++;
}
System.out.println(a+1 +". Word: " + words[a] + " || Counter: "+lastCount.get(a));
}
}
【问题讨论】:
-
通过 "循环正在停止" 看来您的意思是 "我得到 java.lang.IndexOutOfBoundsException: Index 1 out-of-bounds for length 1" 。请具体说明程序如何无法正常工作
-
或者你的意思是
while循环只在第一次工作,即当a == 0?如果是这样,那是因为您从未将i重置为 0。不要在需要变量之前声明它们。如果您在for循环内完成了int i=0;,而不是在顶部声明i,您可能会避免这个问题。 -
谢谢,我尝试调试太多,但无法修复。第一次,我对问题和消除非常小心。下次我会更加小心。 @安德烈亚斯
标签: java loops while-loop counter