java - Java中的while循环
问题描述
我试图通过将句子分成单个单词来制作单词计数器。我尝试通过使用 split 方法(对于对象字符串)来完成此操作。但是,我无法计算单词,因为循环在中途终止。你能帮助我吗?
期望:找出字符串中的单词重复了多少次。
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));
}
}
解决方案
首先,你应该初始化max
and a
; 它消除了混乱并使其更易于阅读。其次,您应该使用嵌套的 for 循环而不是 for 循环和 while 循环。第三,我相信一旦i
到达words.length
,您不会将其重置回 0。当a
为 0 时,i
转到words.length
,并且迭代 1 完成。a
变为 1,但i
仍然是words.length
,所以什么也没有发生。如此重复直到a
变为words.length
,程序停止。几乎什么都没有完成。我相信这个问题可以通过制作只存在于 for 循环中a
的i
局部变量来解决。代码应变为:
public static void main(String[] args) {
int count = 0;
int max = 0;
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(int a=0; a < words.length; a++) {
for(int i=0; i < words.length; i++){
if(words[a].equals(words[i])) {
max = 0;
lastCount.add(a, max+1);
}
}
System.out.println(a+1 +". Word: " + words[a] + " || Counter: "+lastCount.get(a));
}
}