How to set an array

edited October 2013 in How To...

Is there a way to set all the values in an array at once with one line of code? I want to make something where if ENTER is pressed then all the values in an array are set to 255.

Thanks

Answers

  • Answer ✓

    You would have to use a loop

    for(int i = 0; i < array.length; i++)
        array[i] = 255;
    
  • edited October 2013

    You can use the fill() method from java.util.Arrays (you will have to import it first).

    Here's a short sample code:

     
            import java.util.Arrays;
            
            int[] myArray = { 100, 25, 19, 3458 };
            
            void draw() {
            }
            
            void keyPressed() {
              if (keyCode == ENTER) {
                int newVal = (int)random(255);
                println("Filling the array with " + newVal);
    
                Arrays.fill(myArray, newVal); // This is what you need
    
                printArray(myArray);
              }
            }
    

    note: printArray() was introduced in Processing 2.1

Sign In or Register to comment.