我必须检查数组的元素是否与前一个相同(java)

时间:2021-08-01 20:05:12

标签: java

我遵循了网站的建议,但没有找到让我满意的答案。 我必须解决一个学校练习。我有一个数组,我需要检查是否至少有 3 个连续的“a”字符的序列。

public static String alternative(char[] a) {
    String ret = "";
    int consecutiveCounter = 0;
    int i = 1;
     while(consecutiveCounter<3){
         while(i<= a.length){
             if(a[i] =='a' && a[i] == a[i-1] ) {

                consecutiveCounter++;
            } else {
                consecutiveCounter = 0;
            }
            i++;
        }
    }

    if (consecutiveCounter == 3) {
        ret += "there are three consecutive a char";
    } else {
        ret += "there are not three consecutive a char";
    }
    return ret;

}


public static void main(String[] args) {
    char[] a = new char[]{'a', 'a', 'b', 'c', 'a', 'b', 'a'};
    System.out.println(alternative(a));

}

终端给了我这个例外:

线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException:索引 7 超出长度 7 的范围 在 Es1.alternative(Es1.java:9) 在 Es1.main(Es1.java:31)

我无法在不超出数组边界的情况下增加索引 (i) 的值

3 个答案:

答案 0 :(得分:1)

在这里使用 for 循环可能更好,既检查数组的边界,也检查 'a' 的内部计数,并在达到所需限制时尽早返回:

public static String alternative(char[] a) {
    for (int i = 0, n = a.length; i < n; ) {
        for (int count = 1; i < n && a[i++] == 'a'; count++) {
            if (count == 3) {
                return "there are three consecutive 'a' chars";
            }
        }
    }
    return "there are not three consecutive 'a' chars";
}

值得一提的是,String 类(基本上建立在 char 数组上)有几个方法来实现这个功能:

  • String::contains"aabbccaaa".contains("aaa") // true
  • String::indexOf"aabbccaa".indexOf("aaa") // -1, aaa not found
  • String::matches(使用正则表达式):"aabbaaaccaa".matches(".*a{3}.*") // true

答案 1 :(得分:0)

另外,我认为你的外循环不会很好用。
1.假设没有连续的字符,那么consecutiveCounter将保持0并且while(consecutiveCounter<3)不会结束。
2.即使有一两个,但会再次设置为0,并且while(consecutiveCounter<3)不会结束。

答案 2 :(得分:0)

这里有一些建议。

  • 使用 i = 1 to i < a.length 中的 for 循环。那么 i 不会超过数组的最后一个索引。
  • 您只想找到 3 个连续的 'a's。所以将 consecutiveCounter 初始化为 1。
  • 一旦找到第一个连续的对,就增加 consecutiveCounter,现在它是 2,这是正确的。
  • 然后在同一个 if clause 中检查该值是否等于 3。如果是,立即返回字符串(您甚至可能有 4 或 5 个连续的 a's,但您也有 3,所以当第一次遇到 3 的计数。
  • 否则,如果 if 语句失败,则将 consecutiveCounter 重置为 1 并继续循环。
  • 最后,在循环外,返回指示未满足要求的字符串。

注意:如果您试图找到连续 a's 的最大数量,将计数器设置为 1 将不起作用,因为您可能根本没有 a's。但由于您正在寻找一个特定的数字 == 3,所以它工作正常。