Assign values to a multidimensional array using a for loop

0

Good, I'm making a game board (a simple sink the fleet), and to define the boxes I'm using a multidimensional array (x, y). The idea is to initially assign values to these boxes depending on the content (toilet = 0 boat = 1), it seems too gross to assign the values one by one, especially in order to complicate the type of exercise in the future, so I it happens to use a 'For' loop to assign them, should I cover with a 'for' all the boxes and then open secondary loops for the boxes in which there is a ship?

package HundirFlota;

class MyDesk {
    int [][] barcosvivos;

    public MyDesk(){
        this.barcosvivos = new int[5][5];}      

    public MyDesk (int enemydesk[][]){
        this.barcosvivos = new int [5][5];}
}
//Boats life: 0-Water, 1-Life Position, 
/*
 * [0][0][0][0][0]
   [1][0][1][1][1]
   [1][0][0][0][0]
   [1][0][0][0][0]
   [0][0][0][0][0]
*/

The question is what would be the cleanest way to do it. Greetings

    
asked by Pablo León 18.04.2016 в 16:32
source

1 answer

2

In Java, when you initialize an array, its boxes will contain a default value that depends on the data type of the array. In the case of int[][] , the default value for int is 0 , so when doing this:

this.barcosvivos = new int[5][5];

Your array stored in barcosvivos will already find all the boxes initialized with value 0 . You can check this with the following code:

for (int[] interno : this.barcosvivos) {
    System.out.println(Arrays.toString(interno));
}

What will it print:

[0][0][0][0][0]
[0][0][0][0][0]
[0][0][0][0][0]
[0][0][0][0][0]
[0][0][0][0][0]

What you must do is initialize only those boxes with the values you want, such as 1, 2 or the one that best suits your situation. The best thing, for your case, would be to indicate the location (x, y) and orientation (vertical or horizontal) of each boat and then use a cycle for to place the data of each boat on your board.

    
answered by 18.04.2016 / 16:51
source