user3472686
user3472686

Reputation: 23

Is there a way to ignore the counter in a for loop?

I want my for loop to not do the i++ if a certain condition applies.

for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j = j+2) {
                int n = (int)(Math.random()*(474))+1;
                    if(!myList.contains(n)) {
                        myList.add(n);
                        myList.add(n);
                    }
                    else {
                        //Do not do i++ and j = j+2
                    }
            }
        }

Upvotes: 2

Views: 887

Answers (4)

Radu Diță
Radu Diță

Reputation: 14171

You could test the condition in the for loop using the ternary operator and only change the counter variable when the condition is true. This means that you would need to move the condition variable outside the loop. But you could write something like this

for( int i = 0; i < r; cond ? i++ : i )
{
  .... 
 }

Upvotes: 0

user3504707
user3504707

Reputation: 31

for (int i = 0; i < r; ) {
    for (int j = 0; j < c; ) {
            int n = (int)(Math.random()*(474))+1;
                if(!myList.contains(n)) {
                    myList.add(n);
                    myList.add(n);
                    i++;
                    j = j+2;
                }
    }
}

Upvotes: -1

T.J. Crowder
T.J. Crowder

Reputation: 1074266

I want my for loop to not do the i++ if a certain condition applies.

Then you probably don't want a for loop, you probably want a while that only increments in the opposite of the condition where you didn't want the for to. I'd do an example, but it's unclear how you want the condition of the inner loop to affect the outer. The general form of this is:

int i = 0;
while (i < limit) {
    if (/* Condition where you should increment */) {
        ++i;
    }
}

Be careful with the condition, to make sure you don't end up endlessly looping.

Or sometimes looping backward is a better choice, but I don't think that applies in this case.

Upvotes: 7

Patrick J Abare II
Patrick J Abare II

Reputation: 1129

You'll want to move the i++ from the iterator slot. You do not need to fully qualify a for() statement. I.E. for(;;) is legal in java.

for (int i = 0; i < r; ) {
    for (int j = 0; j < c; j = j+2) {
            int n = (int)(Math.random()*(474))+1;
                if(!myList.contains(n)) {
                    myList.add(n);
                    myList.add(n);
                    i++;
                }
                else {
                    //Do not do i++ and j = j+2
                }
        }
    }

Upvotes: 5

Related Questions