Exercise list of numbers ending in 2 with an unknown fault

3

I have an exercise that I have been working on and it turns out that, although it gives me all the results I ask, it throws an exception from ArrayOutOfBounds (on out of range indexes). Does anyone see the fault and correct me please? Thank you very much

``````package ejerciciosGenerales;

import java.util.Scanner;

public class Ejer5 {
// Leer un numeroS y contar cuantoS acaban en 2
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);

System.out.print("Introduzca el total de numeros que desea ingresar: ");

int todosNumeros = scn.nextInt();

int[] numeros = new int[todosNumeros];

System.out.println("Introduzca " + todosNumeros + " numeros: ");

for (int i = 0; i < numeros.length; i++) {

System.out.print("Numero " + (i + 1) + ": ");

numeros[i] = scn.nextInt();

}
System.out.println("Los numeros introducidos son: ");

try {
for (int i = 0; 1 < numeros.length; i++) {

System.out.println(numeros[i]);

}
} catch (Exception exc) {
// TODO Auto-generated catch block
exc.printStackTrace();

}

System.out.println("Y los numeros acabados en 2 son: ");
for (int i = 0; 1 < numeros.length; i++) {
if (numeros[i] % 10 == 2) {

System.out.println(numeros[i]);

}

}
}

}
``````

asked by MikeWazowski 22.11.2016 в 12:29
source

3

That's because you have to compare the value of `i` in the loop and not the value of 1:

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

source
2

If in the loops you set the number 1 as a condition, then the loop will jump when the variable i reaches the end of the created array.

``````for (int i = 0; **1** < numeros.length; i++) {
System.out.println(numeros[i]);
}
``````

You should change 1 by i or a variable that is dynamic and fits the size of the array.