简体   繁体   中英

The increment integer won't increase by 2 in the for loop

This is my code.

for (int i = 0; i<shots.size(); i=i+2){ //I would expect "i" to increase by 2 for every loop.
            i = i%4; //On this line, there is ALWAYS that i==2
            switch (i){
            case 0: boards[1].getTile(shots.get(i),shots.get(i+1)).shoot();
                break;
            case 2: boards[0].getTile(shots.get(i),shots.get(i+1)).shoot();
                break;
            }
            if (gameOver()){
                break;
            }
        }

But when I run the debugger, I see that "i" is reset to 0 every time I hit the loop initializer, and then "i" is set to "2" on the first line inside the loop. I want this to behave like a regular for loop, only that I want "i" to increase by 2 instead of 1 for each iteration. Is there any way I can do that?

Thanks for all help!

I suspect this is your problem

 i = i%4;

Lets look at what i does:

i = 0 is 0
i = i % 4 is the remainder of 0 / 4 which is 0
i = i + 2 is 2
i = i % 4 is the remainder of 2 / 4 which is 2
i = i + 2 is 4
i = i % 4 is the remainder of 4 / 4 which is 0

Thus unless shots.size() is less than 2 you loop forever unless gameOver() becomes true and you break out of the loop. You can do as @Eran suggests and create a new int j to be the mod of i or (since you aren't using j anywhere else) just do this:

switch (i%4)

I think you need two variables :

    for (int i = 0; i<shots.size(); i=i+2){
        int j = i%4; // j will always be either 0 or 2, so the switch statement
                     // will toggle between the two cases
        switch (j){
        case 0: boards[1].getTile(shots.get(i),shots.get(i+1)).shoot();
            break;
        case 2: boards[0].getTile(shots.get(i),shots.get(i+1)).shoot();
            break;
        }
        if (gameOver()){
            break;
        }
    }

For this to work, shots.size() must be even. If it's odd shots.get(i+1) will eventually throw an exception.

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