How to convert this pseudo code to Java without get a java.lang.ArrayIndexOutOfBoundsException

Viewed 448

I am converting a pseudo code to Java to anwers the question "What does the algorithm foo output when the array [2, 3, 5, 7] is entered". I tried so far a code in Java that gives me a java.lang.ArrayIndexOutOfBoundsException error. I can not understand what is wrong if I converted exactly the pseudo code to Java.

This is the pseudo code:

1: x := 0;
2: for i := 1 to n do
3: x := x + A[i];
4: end for
5: if x < 2 then
6: return f alse;
7: end if
8: for i := 2 to x − 1 do
9: if x mod i = 0 then
10: return f alse;
11: end if
12: end for
13: return true;

And here is the code I write:

public class foo {

static int[] A = new int[] { 2, 3, 5, 7 };
static int x = 0;

public static void main(String[] args) {
    System.out.println();
    bb();
}

private static boolean bb() {
    for (int i = 1; i <= A.length; i++) {
        x = x + A[i];
    }

    if (x < 2) {
        return false;
    }

    for (int i = 2; i <= x - 1; i++) {
        if ((x % i) == 0) {
            return false;
        }
    }

    return true;

}

}

With the code I get the error

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at foo.bb(foo.java:14)
at foo.main(foo.java:9)

I know that java.lang.ArrayIndexOutOfBoundsException occurs when we try to access an element of an array, with an index that is negative or more than the size of array itself. But I don't see where I failed converting the pseudo code to Java to get this error. I have to exactly convert the given pseudocode to Java.

Thanks

1 Answers

Java is a zero-based language: All indexes start from 0 and end at length - 1.

Change:

for (int i = 1; i <= A.length; i++) {
    x = x + A[i];
}

To:

for (int i = 0; i < A.length; i++) {
    x = x + A[i];
}
Related