2

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

Miguel Bets
  • 181
  • 1
  • 10
  • 1
    The pseudo code seems to assume that arrays are 1-indexed (i.e. they go from 1 to n), but Java uses 0-indexing (i.e. they go from 0 to n-1). So either change your `for` loop or change your array access to use `A[i-1]` instead. – Joachim Sauer Apr 21 '21 at 17:21
  • "with an index that is [..] more than the size of array itself." ... no, index == size doesn't work either. – Tom Apr 21 '21 at 17:21

1 Answers1

2

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];
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722