Excecute multiple arrays in one line?

Okay I know this probably sounds confusing and it’s most likely impossible, but I want to know if theres a way to tell Processing to do an action with all the different variables in one array. Like that: example[0 to 4] = 999; I’m new, and was hoping to be able to save some space with that. :smiley:

That’s actually a thing in Python, but the closest thing you’re going to get in Java is a for-each loop: https://www.geeksforgeeks.org/for-each-loop-in-java/

2 Likes

Or if you don’t want to deal with all the elements, a simple for loop will do.

for (int i = 0; i < 4; i++) {
  example[i] = 999;
}
1 Like

Docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#fill(int[],int,int,int)

final int[] example = new int[10]; // 10 indexed integer values

void setup() {
  java.util.Arrays.fill(example, 0, 4, 999); // assign value 999 to indices 0 to 3
  println(example);
  exit();
}
2 Likes

@jb4x’s for ( ; ; ) loop example can be turned into 1 single statement too: :innocent:

final int[] example = new int[10]; // 10 indexed integer values

void setup() {
  //java.util.Arrays.fill(example, 0, 4, 999); // assign value 999 to indices 0 to 3
  for (int i = 0; i < 4; example[i++] = 999); // assign value 999 to indices 0 to 3
  println(example);
  exit();
}
6 Likes

What! didn’t know that!

Thanks for the tip!

I sometimes use it in if statement like so:

If ((myVar = fetchData()) = 5) {} 

But I never thought of doing it on a for loop.

And I also realize how off my answer was since he asked for a 1 line statement…

Shouldn’t it be i++ - 1 though? I can’t try now…

Thanks, I never thought of using a for loop :smiley:

Thanks as well! :smiley:

i++ evalutes to i and then increments i up by 1.

So

let i = 0;
console.log(i++);
console.log(i++);
console.log(i);

Will output

0
1
2

To make it increment up by 1 and then evaluate to the old i + 1, use ++i.

There is a good explaination in 30secondsofinterviews.org.

4 Likes

I’ve heard somewhere that in the actual internal implementation for the 2 postfix unary operators (var++ & var--), they 1st cache the variable’s current value before updating it. And then they return that cached original value.

It’s very common to state that the postfix increment unary operator var++ corresponds to var = var + 1 or to var += 1.

However, that’s misguidingly wrong! B/c they correspond to the prefix increment unary operator ++var instead, if they’re used inside expressions!

3 Likes