简体   繁体   中英

Initializing a 2-D Array in java

Little confused why this isn't working could use a little help, I want to set all the values to false:

boolean[][] seatArray = new boolean[4][4];

for(int x = 0; x < seatArray.length; x++){
    for(int y = 0; y < seatArray.length; y++){
        seatArray[x][y] = false;
    }
}

You have to ensure that you are iterating over the correct array element in your inside for loop to set every value to be false . Try this:

boolean[][] seatArray = new boolean[4][4];

    for(int x = 0; x < seatArray.length; x++){
        for(int y = 0; y < seatArray[x].length; y++){
            seatArray[x][y] = false;
        }
    }

EDIT : Your code should still work, but for convention you should still probably do this.

You don't actually need to explicitly set any value.

The primitive boolean defaults to false .

Hence:

boolean[][] seatArray = new boolean[4][4];
System.out.println(seatArray[0][1]);

Output

false

BY defaultif u initialize a 2D boolean array it will contain value as false Lets say you have a two dimensional array as

boolean[][] seatArray=new boolean[4][4];//all the value will be false by default
so it is a 4*4 matrix

boolean[0] represents the the 1st row i.e Lets say it contains value like {true,true,true,true} if you need the value in individual cell you need to iterate 2 for each loop like

    for (boolean[] rowData: seatArray){
                for(int cellData: rowData)
                {
System.out.printn("the indiviual data is" +cellData);
                 cellData=Boolean.false;
                }
            }

Your code should work but here is another solution for filling a 2D array:

    boolean[][] b = new boolean[4][4];

    for (int i = 0; i < b.length; i++)
        Arrays.fill(b[i], false);

Another way to make sense of iterating over multi dimensional arrays is like this.

boolean[][] seatArray = new boolean[4][4];

//Foreach row in seatArray
for(boolean[] arr : seatArray){
    for(int i = 0; i < arr.length; i ++){
        arr[i] = false;
    }
}

如果已经给出了一个恒定大小的数组,请避免使用.length并使用常量。

for(int x = 0; x < 4; x++){for(int y = 0; y < 4; y++){ ... ... }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM