Estoy tratando de devolver los valores de un array de nombres después de ser ingresados por consola, pero me sale este error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2error
No consigo dar con la solución, agradezco de antemano cualquier explicación que puedan darme.
El código es este:
package retoArrayNombres;
import java.lang.reflect.Array;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class reto {
private static Scanner captura;
static int tamanioArray = 0;
public static void main(String[] args) {
capturatamanio();
capturaNombres();
}
public static int capturatamanio() {
System.out.print("Por favor ingrese el tamaño del arreglo: ");
try {
captura = new Scanner(System.in);
tamanioArray = captura.nextInt();
if (tamanioArray > 0) {
System.out.print("Tamaño capturado\n");
}else {
System.out.print("Por favor ingrese un número diferente de 'cero'\n");
}
} catch (Exception e) {
System.out.println("Por favor ingrese un número, las letras no determinan el tamaño\n");
}
return tamanioArray;
}
public static String capturaNombres() {
int i ;
captura = new Scanner(System.in);
String [] nombres = new String[tamanioArray];
for (i = 0; i < nombres.length; i++) {
System.out.print("Por favor ingrese el nombre de la posición " + i + " " );
nombres[i] = captura.nextLine();
}
return nombres[i].toString();
}
}
return nombres[i].toString();
, el valor dei
es igual atamanioArray + 1
(es mayor que el length maximo de nombres). Es porque se genera el error.