【问题标题】:Standing While Loop in JavaJava中的while循环
【发布时间】: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


【解决方案1】:

首先,你应该初始化maxa;它消除了混乱并使其更易于阅读。其次,您应该使用嵌套的 for 循环而不是 for 循环和 while 循环。第三,我相信一旦i 达到words.length,你不会重置它回到0。当a 为0 时,i 转到words.length,迭代1完成了。 a 变为 1,但 i 仍然是 words.length,所以什么也没有发生。如此重复直到a 变为words.length,程序停止。几乎什么都没有完成。我相信这个问题可以通过使 ai 局部变量只存在于 for 循环中来解决。代码应该变成:

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));
}

}

【讨论】:

  • 谢谢,循环正常工作,但计数器的数量只增加了一次。他只见过一次,尽管有相同的词@Roham Bhowmik
  • @Nosteam 在i 循环的迭代过程中if 语句为真的次数无关紧要,因为代码将执行相同每次的事情。 max = 0 后跟 lastCount.add(a, max+1)lastCount.add(a, 1) 相同,例如a = 0,即使words是一个10次同一个词的数组,代码也只会执行lastCount.add(0, 1)十次,导致lastCount包含{0=1}。您的代码实际上并没有计算任何东西。
猜你喜欢
  • 2014-03-29
  • 2018-07-07
  • 2011-01-20
  • 1970-01-01
  • 1970-01-01
  • 2022-09-24
  • 2010-11-26
  • 1970-01-01
相关资源
最近更新 更多