Reputation: 283
I'm currently writing a for loop to go through a 2D with 38 elements. However, some of those elements are null and I want the for loop to simply skip over them (because in the puzzle I'm solving they have no moves associated with them). A quick search revealed that I can skip an iteration with a simple continue
statement in an if
statement at the beginning of the for
loop. However, I want to skip multiple iterations, and the if statement I wrote isn't working:
for (int i = 0; i < triplets.length; i++) {
if (i == 18 || 19 || 25 || 26 || 28 || 29 || 31 || 32) {
continue;
}
Is there an alternative to making 8 individual if
statements or am I stuck with that?
Upvotes: 0
Views: 493
Reputation: 3836
Is there an alternative to making 8 individual if statements or am I stuck with that?
you can create excluding List
and execute your code when current triplet doesn't exist in it (code is more concise without continue
calls).
List<Integer> exclude = Arrays.asList(18, 19, 25, 26, 28, 29, 31, 32);
for (int i = 0; i < triplets.length; i++) {
if (!exclude.contains(i)) {
....//your code
}
}
If the exclude list is big then it is a good idea to replace ArrayList
with HashSet
, which has O(1) search complexity instead of O(N) (but consumes about 5.5 times more memory for each element)
Upvotes: 2
Reputation: 9648
You are not giving the condition properly. It should be something like this:
if (i == 18 || i == 19 || i == 25 || i == 26 || i == 28 || i == 29 || i == 31 || i == 32) {
continue;
}
Alternatively, I would suggest you to do something like this instead:
Create a HashSet
and put the values to be compared in it.
Check if HashSet
contains i
and if yes then continue the loop.
Set<Integer> set = new HashSet<>();
set.add(18);
set.add(19);
set.add(25);
set.add(26);
set.add(28);
set.add(29);
set.add(31);
set.add(32);
if(set.contains(i)) {
continue;
}
Upvotes: 5