增量整数不会在for循环中增加2

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

这是我的代码。

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;
            }
        }

但是当我 运行 调试器时,我看到每次我点击循环初始值设定项时 "i" 都被重置为 0,然后 "i" 被设置为“2”循环内的第一行。我希望它表现得像一个常规的 for 循环,只是我希望 "i" 每次迭代增加 2 而不是 1。有什么办法可以做到吗?

感谢大家的帮助!

我怀疑这是你的问题

 i = i%4;

让我们看看 i 做了什么:

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

因此,除非 shots.size() 小于 2,否则您将永远循环,除非 gameOver() 变为真并跳出循环。你可以按照@Eran的建议去做 并创建一个新的 int j 成为 i 的 mod 或者(因为你没有在其他任何地方使用 j)就这样做:

switch (i%4)

我想你需要两个变量:

    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;
        }
    }

要实现此功能,shots.size() 必须是偶数。如果是奇数 shots.get(i+1) 最终会抛出异常。