我试图通过将句子分为单个单词来使单词反击。我尝试通过使用split方法(针对对象String)来实现此目的。但是,由于循环在中途终止,因此我难以计算单词数。你能帮我吗?
所需:找出一个单词在一个单词中重复多少次。
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));
}
}
答案 0 :(得分:2)
首先,您应该初始化a
和i
;它消除了混乱并使其更易于阅读。第二,您应该使用嵌套的for循环,而不是for循环和while循环。第三,我相信一旦words.length
到达a
,您就不会重置回到0。i
为0时,words.length
到a
,迭代1完成。 i
转到1,但是words.length
仍然是a
,因此什么也没发生。重复执行直到words.length
变为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));
}
这两个仅在for循环中存在的局部变量来解决此问题。该代码应变为:
{{1}}
}