Issue
I have a Java code with 2d arrays and i want to rewrite this code to look like it has less code than i wrote before.
The main task of my code is to have cubes in 1.
Is there any ideas how to fix it?
My Data:
2 0 0 1 1 0 0 0
0 0 1 0 0 1 0 0
0 0 0 0 0 0 0 0
1 0 1 0 0 1 0 1
1 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0
0 0 1 0 0 1 0 0
0 0 0 1 1 0 0 0
My Code:
for(int i = 0; i < map.length; i++) {
for(int j = 0; j < map.length; j++) {
if(map[i][j] == map[0][3]) {
gc.fillRect(i, j, 1, 1);
}
if(map[i][j] == map[0][4]) {
gc.fillRect(i, j, 1, 1);
}
if(map[i][j] == map[1][2]) {
gc.fillRect(i, j, 1, 1);
}
if(map[i][j] == map[1][5]) {
gc.fillRect(i, j, 1, 1);
}
if(map[i][j] == map[3][0]) {
gc.fillRect(i, j, 1, 1);
}
if(map[i][j] == map[3][2]) {
gc.fillRect(i, j, 1, 1);
}
if(map[i][j] == map[3][5]) {
gc.fillRect(i, j, 1, 1);
}
if(map[i][j] == map[3][7]) {
gc.fillRect(i, j, 1, 1);
}
if(map[i][j] == map[4][7]) {
gc.fillRect(i, j, 1, 1);
}
if(map[i][j] == map[6][2]) {
gc.fillRect(i, j, 1, 1);
}
if(map[i][j] == map[6][5]) {
gc.fillRect(i, j, 1, 1);
}
if(map[i][j] == map[7][3]) {
gc.fillRect(i, j, 1, 1);
}
if(map[i][j] == map[7][4]) {
gc.fillRect(i, j, 1, 1);
}
}
}
Solution
You are compairing every field in your map with every field in your map that equals 1
. So you could just check if the value of one field is 1:
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[0].length; j++) {
if (map[i][j] == 1) {
gc.fillRect(i, j, 1, 1);
}
}
}
Answered By - Japhei
Answer Checked By - Mildred Charles (JavaFixing Admin)