java.lang.ArrayIndexOutOfBoundsException: 0

0

I have this class in java:

public class matriz {
    private int tamMatriz;
    private int[][] mainMatriz = new int[tamMatriz][tamMatriz];

    public matriz (int tamaño){
        tamMatriz = tamaño;

    }

    public void instanciarMatriz(){
        for (int i=0; i<=this.getTamaño()-1; i++){
            for (int j=0; j<=this.getTamaño()-1; j++){
                mainMatriz[i][j]=1;
            }
        }
    }

And I throw the error but I do not know why it can be! Any ideas?

    
asked by Munstar 02.11.2018 в 08:34
source

1 answer

1

Easy, when you create the object, the value of tamMatriz is equal to 0, so it creates an empty matrix and when traversing it tamMatriz has already been assigned so it tries to traverse non-existing elements.

What you have to do is initialize the array in the constructor after assigning the value of tamMatriz .

public class matriz { 
    private int tamMatriz;
    private int[][] mainMatriz;

public matriz (int tamaño){
    tamMatriz = tamaño;
    mainMatriz = new int[tamMatriz][tamMatriz];    
}
public void instanciarMatriz(){
    for (int i=0; i<=this.getTamaño()-1; i++){
        for (int j=0; j<=this.getTamaño()-1; j++){
            mainMatriz[i][j]=1;
        }
    }
}

PS: The names of the classes must go with the first in capital letters according to the style rules.

    
answered by 02.11.2018 в 08:44