使用foreach时出现异常,但使用普通for循环可以正常执行。

huangapple go评论61阅读模式
英文:

Getting exception when using foreach but regular for loop executes well

问题

使用普通的for循环,可以得到正确的输出,但是使用for each循环会抛出ArrayOutOfBound异常。有人能解释一下吗?

public class FindTheDiff {
    public static void main(String args[]){
        System.out.println(isAnagramRecursion("all","laa"));
    }

    private static boolean isAnagramRecursion(String param1, String param2) {
        int[] arr = new int[122];
        char[] param1Lower = param1.toLowerCase().toCharArray();
        char[] param2Low2 = param2.toLowerCase().toCharArray();

        for (char ch1 : param1Lower) {
            arr[ch1] = arr[ch1]+1;
        }

        for (char ch2 : param2Low2){
            arr[ch2] = arr[ch2]-1;
        }

        for (int i : arr) {
            if(arr[i] != 0)
                return false;
        }
        /*for (int i = 0; i < arr.length; i++) {
            if(arr[i] != 0)
                return false;
        }*/
        return true;
    }
}
英文:

Using regular foloop, getting correct output, using for each loop throws ArrayOutOfBound exception. Can anyone explain?

public class FindTheDiff {
public static void main(String args[]){
    System.out.println(isAnagramRecursion(&quot;all&quot;,&quot;laa&quot;));
}

private static boolean isAnagramRecursion(String param1, String param2) {
    int[] arr = new int[122];
    char[] param1Lower = param1.toLowerCase().toCharArray();
    char[] param2Low2 = param2.toLowerCase().toCharArray();

    for (char ch1 : param1Lower) {
        arr[ch1] = arr[ch1]+1;
    }

    for (char ch2 : param2Low2){
        arr[ch2] = arr[ch2]-1;
    }

    for (int i :arr) {
        if(arr[i] != 0)
            return false;
    }
    /*for (int i = 0; i &lt; arr.length; i++) {
        if(arr[i] != 0)
            return false;
    }*/
    return true;
}

}

答案1

得分: 2

这是错误的循环。在执行forEach循环时,您是对值进行迭代,而不是索引。在您的情况下,正确的forEach循环应该是:

for (int arrValue : arr) {
    if (arrValue != 0)
        return false;
}
英文:

This is the wrong loop. When doing a forEach loop, you iterate over the value, not the index. The correct forEach loop in your case should be:

for (int arrValue :arr) {
    if(arrValue != 0)
        return false;
}

答案2

得分: 1

以下是翻译好的内容:

在这里,i 不是数组的索引,它是数组的。但在常规循环中,i 是索引。

for (int i : arr) {
    if (arr[i] != 0)
        return false;
}

使用数组的值意味着在条件中使用 i

for (int i : arr) {
    if (i != 0)
        return false;
}
英文:

Here i is not the index of the array, it's the value of the array. But in the regular loop i is the index.

for (int i :arr) {
    if(arr[i] != 0)
       return false;
}

Use the value of the array means i in if condition

for (int i :arr) {
    if(i != 0)
        return false;
}

huangapple
  • 本文由 发表于 2020年7月25日 21:49:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63089145.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定