-1

So I have an array that I allocate to store 5 integers, then take those integers and multiply them by another variable (cyclicNum) however I keep getting an ArrayOutOfBoundsException error. Can someone please explain where the issue is? To my knowledge, I'm not going out of bounds of the given indices, though I may be wrong. I hardcoded a 2 in the second loop where my cyclicNum variable would go to test and still got the same error. Here is my code thus far:

    Scanner prompt = new Scanner(System.in);

    System.out.print("Enter a number to perform cyclic computation on: ");

    int cyclicNum = prompt.nextInt();

    System.out.println("Enter how many numbers you would like to multiply by: ");

    int length = prompt.nextInt();

    System.out.println("Enter the numbers: ");

    int[] multiples = new int[length];

    for(int i = 0; i < multiples.length; i++){
        multiples[i] = prompt.nextInt();
    }

    for(int j = 0; j < multiples.length; j++){
        System.out.println(multiples[j * 2]);
    }

1 Answers1

0

The last for look gets the array element j * 2, which is going to be out of range for at j / 2.

If the length of multiples is 5, then the index elements the loop tries to access is 0, 2, 4, 6, 8, the last two are outside the length of the array.

Scott Sosna
  • 1,443
  • 1
  • 8
  • 8