Exception in thread error "main" java.lang.ArrayIndexOutOfBoundsException: 0 at gestionDesposito.main (gestionDesposito.java:13)

0

I do not know how to solve this error (I think it's because I do not aim well at the position of the array but I do not have much idea how to fix it).

import java.util.*;
public class gestionDesposito {

public static void main(String[] args) {
    int tamanio=0;
    Deposito[] d=new Deposito[tamanio];
    Scanner sc= new Scanner(System.in);

  System.out.println("Escriba el numero de despositos a crear entre 4 y 10: ");
  tamanio=sc.nextInt();
  if(tamanio>=4 && tamanio<=10){
      for(int i=0;i<tamanio;i++){
          d[i]=new Deposito("0001",10,30);
          System.out.println(d[i]);
      }

  }

  sc.close();
}

}
    
asked by iHack 20.10.2017 в 12:07
source

1 answer

2
int tamanio=0;
Deposito[] d=new Deposito[tamanio];

You are creating an array of length 1. And then if you enter a "5" by the console you are trying to access an array of length 5.

That is, you ask the user to indicate the length, but you are not assigned to the array.

Solution: You should put it after the Scanner:

int tamanio=0;
Scanner sc= new Scanner(System.in);

  System.out.println("Escriba el numero de despositos a crear entre 4 y 10: ");
  tamanio=sc.nextInt();
Deposito[] d=new Deposito[tamanio];

Note: If you want the size of the array to be the same length as the user indicates, subtract 1 from the variable tamanio . Since if you enter a 5, a array[5] has 6 positions.

    
answered by 20.10.2017 / 12:14
source