Java Array Storage Error

Asked

Viewed 76 times

1

I am making a code where the user needs to define a vector of size N, and fill it, however, after informing the vector size, and informing the first value, the following error appears:

Exception in thread "main" java.lang.Arrayindexoutofboundsexception: 0 tp01.Programex1.main(Programex1.java:22)

Follow the code below:

public static void main(String[] args) {

    
    int tamanhoVetor = 0;
    int i;
    float vet[] = new float[tamanhoVetor];
    
    
    Scanner sc = new Scanner(System.in);
    System.out.println("Informe o tamanho do vetor desejado: ");
    tamanhoVetor = sc.nextInt();
    
    for (i = 0;i<=tamanhoVetor;i++)
    {
        System.out.printf("Informe o valor: ");
        vet[i] = sc.nextFloat();
        
    }

1 answer

4


You created the array with zero size. The fact that you changed the value of the variable tamanhoVetor then does not cause the array to change size. So, first read the size and then create the array:

int tamanhoVetor = sc.nextInt();
float vet[] = new float[tamanhoVetor];

Another detail is that arrays are indexed at zero, that is, if the size is N, the positions go from 0 to N-1. So in the loop one should use < instead of <=:

for (i = 0; i < tamanhoVetor; i++)
    etc...

But maybe I don’t even have to keep the size:

float vet[] = new float[sc.nextInt()];
for (int i = 0; i < vet.length; i++)
    etc...

Also note that you do not need to declare the variable i at the beginning of the code, you can do it within the for. This makes clearer the scope of the loop, indicating that it is only used there in that loop.

  • Problem solved, very sheltered by friendly help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.