0

I've been learning to code recently, but unfortunately iterating through arrays and understanding their Length property and not going out of bounds eludes me.

I have the following exercise that I need to solve in Java - input a few numbers, parse them and put them into an array then get the three largest numbers in it and print them in descending order. I managed to do it, but I did need to look up the last part, as I was getting ArrayIndexOutOfBoundsException. I have hardcoded the values in the Array, in order to try and understand it, but I'd appreciate some help on the matter.

Here is my solution:

    int[] numbers = {1, 2, 3, 4, 5, 6};

    Arrays.sort(numbers);

    int count = Math.min(3, numbers.length);
    for (int i = 0; i < count; i++) {
        System.out.println(numbers[i + numbers.length - 1]);

What I am trying to do here is print them in ascending order, as printing them in descending will be numbers[numbers.length - 1 - i]. On my example I am getting OutOfBounds. If I do i + numbers.length - 3 it works.

Will someone be so kind as to explain why? I know it's a stupid question but I just can't seem to understand it.

McGringo
  • 3
  • 3
  • numbers array has indexes ranging from 0 to 5. In the println statement we are adding 5 (which is length of the array - 1) to the 'i' in the first iteration of the loop it gives the last element of the array . during second iteration of the loop 5 is added to i(which is 1 now) equals 6 but there are not enough values in your array to fetch the value. Which gives outofbounds exception. array subscripts start at 0 in Java – Praneeth Gudumasu Aug 03 '18 at 13:34
  • why do you have a 'count' variable? just print out both i and count as first line of your loop, maybe that 'll help making some things clear – Stultuske Aug 03 '18 at 13:35
  • As part of learning to code, it would help immensely once you get familiar with the debugger in your favorite IDE – OneCricketeer Aug 03 '18 at 13:43
  • @PraneethGudumasu Right, I got it now. I am in essence combining the value of i and the length of the array but the entire thing is actually an Index I want retrieved. So in the first iteration of the loop i = 0 + numbers.length - 3 which is 6 - 3 = 3. The result is 3, as in "Give me what is at index 3", which in my case is the number 4. – McGringo Aug 03 '18 at 13:45
  • @Stultuske The original thing had the user input the numbers which I wanted to sort and print the largest three. I forgot to remove the count after hardcoding the input of the array and posting, sorry. – McGringo Aug 03 '18 at 13:52

4 Answers4

2

Image that the array is like a chain of objects. You can always access any of those objects if you know its index. So in the case you have an array of length 9 that contains the first 9 positive integer you will have valid indexes through 0 to 8.

 0  1  2  3  4  5  6  7  8
[1][2][3][4][5][6][7][8][9]

to print out the the values inside the array you could use:

for (int i = 0; i < values.length; i++) {
    System.out.println(values[i]);
}

and if you would like to backward print it then you should start from it's last index and decrement the i until it greater or equal to the starting index of the array:

for (int i = values.length - 1; i >= 0; i--) {
    System.out.println(values[i]);
}

Whenever you try to access an index that is out of the bound of valid indexes it will result to IndexOutofboundsException. So if you like to invoke any arithmetics with calculating the indexes be aware of the fact that you have only few valid values for it.

dbl
  • 1,063
  • 8
  • 15
  • Great explanation! When I was first learning my professor taught us about Arrays in the context of Excel spreadsheets. A single Array is a column starting at A[0], going through A[n]... Once he explained it like that to me, it clicked. Maybe that might work for others as well. – Dan Aug 03 '18 at 13:45
  • Since my education started at early age in high school and we used to code on pascal/C I'll always visualize an array as a matrix. And in this case the matrix has only one row... – dbl Aug 03 '18 at 14:01
1

So in this context let's look at it in terms of the minimum and maximum values that the array access can have

So for the minimum value of i (0), we get i + numbers.length - 1 = 0 + 6 - 1 = 5

and for the maximum of i we either get 3 or numbers.length:

In the case of 3: i + numbers.length - 1 = 3 + 6 - 1 = 8

In the case of numbers.length we get i + numbers.length - 1 = 6 + 6 - 1 = 12

You need to make sure that the possible values that the array will iterate between is always going to give a value within the bounds of the array (as clearly this does not)

Expired Data
  • 649
  • 4
  • 12
0

Tried to run

for (int i = 0; i < count; i++) {
    System.out.println(i + numbers.length - 1);
}

It prints:

5 6 7

Your array has 6 items and is indexed from 0 to 5. When you try to get item that has index >=6 it throws ArrayIndexOutOfBoundsException

Sann Tran
  • 124
  • 4
0

If you want to print them in descending order use

System.out.println(numbers[numbers.length - 1 - i])