This error is due to the attempt to access the first element (Index 0
) of arr2
, whereas arr2
has no element (length 0
) because you declared her with int[] arr2= {}
, without any element between the keys.
In the loop you are declaring b
as a.length-1
, which makes the loop never check the last element of a
, because he’s on the index a-length-1
, and the condition is i < b
, for example:
a.length: 5;
b: a.length-1 = 4;
while (i < b); // o while só passará pelas posições 0, 1, 2 e 3, pois são menores que b (4)
Another thing I noticed was that you assign arr2[i] = a[i]
, leaving empty spaces if there are even numbers before an odd, because arr2 will be assigned in the position i
, for example:
// Usando o seu código, porém assumindo que arr2 possui um tamanho suficiente
a: [0, 4, 2, 87, 6, 9, 3]
arr2: [ , , , 87, , 9, 3]
To correct this, use a variable that stores the current index of arr2
:
public static void maiorValorImpar(int[] a) {
int b = a.length; // Correção da não verificação do último elemento
int[] arr2 = new int[b];
int i = 0, j = 0; // j guarda onde será colocado o próximo número em arr2
while(i < b) {
if(a[i]%2 != 0) {
arr2[j]= a[i];
System.out.println(arr2[j]);
j++;
}
i++;
}
}
When working with arrays you don’t initially know the size, I recommend using Arraylist (documentation) (w3schools), so you don’t need to allocate spaces in the array that you might not use, like on line 3 of my example (int[] arr2 = new int[b];
).
Not directly related, but make a habit of giving names that really indicate what each thing does.
maiorValorImpar
, for example, it might confuse someone else (or even yourself), since the code is not checking the highest odd value, but copying all the odd ones to another array (something likecopiarImpares
would be better, for example). The same goes for variables:impares
would be much better thanarr2
,numeros
it would be better ifa
, etc. It may seem a silly detail, but significant names can help even in reasoning when you are assembling logic...– hkotsubo
truth, thank you very much, I’ll take your advice into consideration! :)
– Micaela