1

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.

2
  • 1
    Looks reasonable. What happens when you run it? Commented Sep 1, 2015 at 15:40
  • It would run, but since I was using a really basic way to test if it was indeed replacing all of the elements with 867, I was unsure if it was doing what it was supposed to be doing. It's all sorted out now though. Commented Sep 1, 2015 at 19:15

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hey, thanks a lot man! I really appreciate it, and this helped me to understand both ways of doing this. (the for loop and the Arrays.fill)
@GL007 Glad I could help.
0

Use the following line inside your loop:

pixels[i][j] = 867;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.