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.