[英]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”都将重置为0,然后在循环的第一行中将“ i”设置为“ 2”。 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.
我希望它表现得像常规的for循环,只是我希望“ i”在每次迭代中增加2而不是1。 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
在做什么:
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. 因此,除非
shots.size()
小于2,否则您将永远循环播放,除非gameOver()
变为true并退出循环。 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: 您可以按照@Eran的建议进行操作,并创建一个新的int
j
作为i
的模或(因为您在其他任何地方都没有使用j
),只需执行以下操作:
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. 为此,
shots.size()
必须是偶数。 If it's odd shots.get(i+1)
will eventually throw an exception. 如果很奇怪,
shots.get(i+1)
最终将引发异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.