0

I'm doing a short lab for school where it takes 10 integers from scanner input and stores them in an array, then copies the data to a second array, then prints the first array forwards, and the second array backwards.

code:

import java.util.Arrays;
import java.util.Scanner;
public class APSummerLab00
{  

   public static void main(String args[])
   {
       int[] array = new int[10]; 
       int[] array2 = new int[10];
       int one, two, three, four, five, six, seven, eight, nine, ten;
       Scanner input = new Scanner(System.in);

       array[1] = input.nextInt();
       array[2] = input.nextInt();
       array[3] = input.nextInt();
       array[4] = input.nextInt();
       array[5] = input.nextInt();
       array[6] = input.nextInt();
       array[7] = input.nextInt();
       array[8] = input.nextInt();
       array[9] = input.nextInt();
       int x = 10;

       for(int i = 0; i<= array.length; i++)
       {
         array2[x] = array[i];
         x--;
       }
   System.out.println(Arrays.toString(array));
   System.out.println(Arrays.toString(array2));
   }
}

On the line in the for loop array2[x] = array[i]; I get the error

"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10"

basically with that line I used a for loop that increments by 1 from 0, and I want to say array2 is going to increment by -1 and make the array2 the backwards version of array.

  • 1
    `int[] array2 = new int[10];` `int x = 10;` `array2[x]` That should be enough of a hint. Arrays start with the index 0 not 1. – Ben Jun 14 '18 at 07:01
  • 1
    You have 10 elements in your array. You are trying to access the (non-existant) 11th element. remember: arrays are 0-based, meaning your indexes go from 0 to (array.length - 1) (in your case: 9) – Stultuske Jun 14 '18 at 07:01
  • I changed x to 9, so shouldn't the error not happen, when x is 9 it should only go down so I'm confused as to why it would be accessing the wrong element? – carteeeeeeer Jun 14 '18 at 07:08
  • int x = 10; array2[x] = array[i]; because with these two lines, you tell it to – Stultuske Jun 14 '18 at 07:11
  • Which is the general rule. "Why is it doing the wrong thing" -> "Because you coded it to do exactly that". Or in other words: Working as expected. – Ben Jun 14 '18 at 07:15
  • Also `for(int i = 0; i<= array.length; i++)`. You don't want to have `i == array.length` – AxelH Jun 14 '18 at 07:32

0 Answers0