How to register values in a two-dimensional array?

Asked

Viewed 33 times

0

Java 

I’ve tried it this way before, but it’s not working. Returns error message: Index 0 out of Bounds for length 0


    private double[][] salarios = {{},{},{},{},{}};

    public  void cadastrarCargos(){
        for (int i = 0; i < 5; i++){
            for (int j = 0; j < 2; j++){
                salarios[i][j] = num.nextDouble();
            }
        }
    }

1 answer

0

In Java the size of the arrays are fixed, that is, once you create the X-size array you cannot add more elements to it. So when you create an array {{},{},{},{},{}} you say they will all have size zero of elements.

This is exactly why this error is being generated. You are trying to access a space in the array that does not exist. The solution to solve this problem would be for you to declare how many positions the array will have.

private double[][] salarios = {{0,0},{0,0},{0,0},{0,0},{0,0}};

If you want to create an empty "array" to gradually add elements, use an ArrayList. With it you can create as many elements as you want without having to declare their size before.

See this example below:

import java.util.ArrayList;

public class Main{
    public static void main(String[] args){

        ArrayList agenda = new ArrayList();

        for (int i = 0; i < 10; i++){
            agenda.add(i);
        }
        System.out.println(agenda);
    }
}
  • Thank you so much for the @Jeanextreme002 explanation

Browser other questions tagged

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