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

时间:2015-03-24 13:43:24

标签: java loops for-loop integer increment

这是我的代码。

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

但是当我运行调试器时,我看到&#34;我&#34;每次点击循环初始化程序时重置为0,然后&#34; i&#34;设置为&#34; 2&#34;在循环内的第一行。我希望这个行为像一个常规for循环,只有我想要&#34;我&#34;每次迭代增加2而不是1。我有什么方法可以做到吗?

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

我怀疑这是你的问题

 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)

答案 1 :(得分:2)

我认为你需要两个变量:

    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)最终会抛出异常。