繁体   English   中英

在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()变为true并退出循环。 您可以按照@Eran的建议进行操作,并创建一个新的int j作为i的模或(因为您在其他任何地方都没有使用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)最终将引发异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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