You do not say in the question what the error is. What you're having is NullPointerException
. The assignment formulas you use are not the problem and are correct.
The reason for giving error is because the array is created initially containing null
in all positions. And when you do tabuleiro[l][c].posicLinha
, tabuleiro[l][c]
will be null
and try to access posicLinha
null
will NullPointerException
.
The simplest and easiest solution to this problem is to add this at the beginning of% internal%:
tabuleiro[l][c] = new Coordenadas();
This will make your code run, but it still will not print what you want because you give for
to a number, give another print
soon then without adding space, nor line wrapping and nothing by making the numbers stick, and for each coordinate you do this by making all the numbers stick to each other forming a single digit language at the end in a single line with no spaces or commas and nothing in between. By using what is below, this is resolved:
System.out.println(tabuleiro[l][c].posicLinha + ", " + tabuleiro[l][c].posicColuna);
With these two fixes, your code will behave as expected. However, your code still suffers from other structural issues, although it works anyway (but will probably break if you make any changes). Note that to create the array you use an empty, useless instance of print
that only exists so that you can call the Coordenadas
method. This can be solved by using the atribPosic
modifier in the method, thus dispensing with the need for an instance to use it.
Also, not putting visibility modifiers in your fields / attributes is not usually a good idea. You hardly intended to use package visibility. In addition, class names should preferably be nouns in the singular, and therefore static
would be a better name than Coordenada
.
There is also no need or purpose in "eating" some letters of variable names and methods, and therefore Coordenadas
is better than atribuirPosicao
. The same goes for atribPosic
and posicLinha
that could be posicColuna
and posicaoLinha
, but simply posicaoColuna
and linha
is simpler.
Your code with these fixes and changes all looks like this:
public class Coordenada {
private int linha;
private int coluna;
public static void atribuirPosicao() {
Coordenada[][] tabuleiro = new Coordenada[8][8];
for (int l = 0; l < 8; l++) {
for (int c = 0; c < 8; c++) {
tabuleiro[l][c] = new Coordenada();
tabuleiro[l][c].linha = 100 + 50 * l;
tabuleiro[l][c].coluna = 100 + 50 * c;
System.out.println(tabuleiro[l][c].linha + ", " + tabuleiro[l][c].coluna);
}
}
}
public static void main(String[] args) {
Coordenada.atribuirPosicao();
}
}
Finally, I recommend that you see this other answer of mine that I posted see another question to understand what causes a coluna
.