简体   繁体   中英

How to change all elements in a 2D Array to the same value using for loops in java

This is my first time asking a question here, so forgive me if my formatting is a little sloppy.

I need to know how to set all the elements of a 2D Array to the same value, using for loops, with Java.

I was able to get this far:

import java.util.Arrays;

public class TheArray{
    public static void main (String[] args){

        int[][] pixels = new int[768][1024];

        for(int i = 0; i < pixels.length; i++){

            for(int j = 0; j < pixels[i].length; j++){
                Arrays.fill(pixels[i], 867);


            }

        }

    }
}

However I have no idea if I have done it right. So all I want it to do is make all of the elements of the 2D array be 867.

You don't need to use Arrays.fill if you're already using for loops. Just do:

for(int i = 0; i < pixels.length; i++){
    for(int j = 0; j < pixels[i].length; j++){
       pixels[i][j] = 867;
    }
}

Arrays.fill would be used instead of the inner for loop.

在循环中使用以下行:

pixels[i][j] = 867;

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