[英]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.