The error of ta because you try to access elements that do not exist outside the array in the for
, and in particular, in the statement num[i] = sc.nextInt();
by the condition i <= tam
.
If the array has n elements, you are trying to access the element immediately following the last element, which does not exist, so an exception is thrown that indicates that the index is outside the index range of the array.
This happens because in Java, as well as in most programming languages (not all), the indexes of an array, or even of an ordered collection (like a sequential list), start at 0 and end at n -1, if the array has n elements.
For example, if we have an array with two elements, the indexes to access will be 0 for the first, and 1 for the second.
int[] dos = new int[2]; // Se crea un array de tamaño 2
dos[0] = 1; // dos[0] hace referencia al primer elemento
dos[1] = 2; // dos[1] hace referencia al segundo y último elemento
dos[2] = 3; // error: un array con dos elementos no tiene tercer elemento
Therefore, when you go over an array of size n, you have to do it from 0 to n-1.
int[] numeros = new int[10];
for (int i = 0; i < 10; i++)
numeros[i] = i;
In this case, i
will take values between 0 and n-1 (n iterations), so it will not leave the index range of the array. Notice that I have put i < 10
and not i <= 10
, because in this way, the last iteration will be when i
is worth 9 (indexes go from 0 to 9 in an array of 10 elements).
The most correct thing, however, is not to use literals, but to do so by referring to the size of the array, especially if it is created based on the size the user says. For example.
int[] numeros = new int[/* tamaño */];
for (int i = 0; i < numeros.length; i++)
numeros[i] = i;
You can also make a route from 1 to n, but when you access the array, you subtract 1 from the index so that it goes from 0 to n-1.
int[] numeros = new int[/* tamaño */];
for (int i = 1; i <= numeros.length; i++)
numeros[i - 1] = i;
In this case, yes you put i <= tam
.