简体   繁体   中英

Java for loop with condition not incrementing

This might be a silly question but I'm confused.

I have a for loop that excludes a given iteration (a random number). It works for any random number chosen that's greater than 0. However, if it's zero, it never does a single iteration:

int x;
for (x = 0; ((x < 2) && (x != r)); x++) {
    // do something if (x != r)

}
System.out.println("X : " + x);

For the example that it's not working, r = 0 . Shouldn't that mean it should skip the first iteration but does the second?

The above println yields "X : 0".

Any help? Thanks!

If you only want to skip the first iteration, you must move the x != r condition inside the loop. Having the x != r condition in the loop's condition means the loop will never be entered if both r and x are initialized to 0 , since the loop terminates when the loop's condition becomes false.

for (x = 0; x < 2; x++) {
    if (x != r) {
    // do something if (x != r)
    }
}
for (initialization; termination condition; increment) {
    statement(s)
}

Above code will run:

    initialization
    termination condition
    statement
    increment

    termination condition
    statement
    increment

    termination condition
    statement
    increment

    ....

So you should remove condition x != r because before it runs statement for first time, it check that condition and return false.

You should note that. without condition x != r , your loop is run only twice: x = 0 and x = 1. Maybe in your code, those value (0 and 1) doesn't output any value.

我认为,如果您放置(r> = 0),然后直接从0中选择随机数生成,那将很好。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM