I believe my mistake is in the matrices, or type conversions, but how to solve?

Asked

Viewed 52 times

3

I’m new to java and I have to make a tetris. In this class in particular, I create 2 control matrices to manage the positions of the pieces on the screen, but it’s giving error. Does anyone have a little time to help the newbie?

package jogo;

import java.awt.Point;

public class MapeiaTela {
int[][] tela1 = new int[12][16];
Point[][] tela2 = new Point [12][16];
int i;
int j;
int x, y;
int largura=0,altura=0;
//Point coord;

public MapeiaTela(){

    for(i=0; i<12; i++){
        for(j=0; j<16; j++){
            tela1[i][j] = 0;
        }
    }

    for(i=0; i<12; i++){
        for(j=0; j<16; j++){

            tela2[i][j].x=largura;
            tela2[i][j].y=altura;

            largura += 50;
        }
        altura +=50;
    }
}

public void validar(Blocos b){

    x=(int )b.x;
    y= (int)b.y;

    for(i=0;i<12; i++){
        for(j=0; j<16; j++){
            if(tela2[i][j].x == x-50 && tela2[i][j].y == y-50 ){
                tela1[i][j] = 1;
            }
        }
    }
}

}

the error is as follows :

Exception in thread "main" java.lang.NullPointerException
at jogo.MapeiaTela.<init>(MapeiaTela.java:28)
at jogo.Principal.main(Principal.java:20)

2 answers

2


The problem is that you are assigning values to a null object.

You need to instantiate a Point before assigning attribute values x and y.

import java.awt.Point;

public class MapeiaTela {

    int[][] tela1 = new int[12][16];
    Point[][] tela2 = new Point[12][16];
    int i;
    int j;
    int x, y;
    int largura = 0, altura = 0;
    //Point coord;

    public MapeiaTela() {

        for (i = 0; i < 12; i++) {
            for (j = 0; j < 16; j++) {
                tela1[i][j] = 0;
            }
        }

        for (i = 0; i < 12; i++) {
            for (j = 0; j < 16; j++) {

                tela2[i][j] = new Point(); /* Alteração aqui */
                tela2[i][j].x = largura;
                tela2[i][j].y = altura;

                largura += 50;
            }
            altura += 50;
        }   
    }   
}

1

Try

Integer i;
Integer j;

x = ( Integer ) b.x;
y = ( Integer ) b.y;

Browser other questions tagged

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