Java-根据条件将for循环计数器调回 [英] Java - Turning the for-loop counter back based on a conditional
问题描述
以下是我的大学作业代码的一部分.
The following is part of the code for my college assignment.
else if (!codeList.contains(userCode)) {
i--; // i is the counter for the for-loop
}
else if (userQuantity[i]==0) {
i--;
}
第一部分确保如果用户输入错误的代码,则计数器i不会递增1,或者说,它会从最近递增的计数器中减去1.这部分工作正常.
The first part makes sure that if the user enters the wrong code, the counter i does not increment 1, or rather, it subtracts 1 from the recently incremented counter. This part works fine.
但是第二部分似乎是我遇到的问题.userQuantity []是一个int数组,它必须是一个数组.这似乎对代码没有任何作用.即使为该数量输入了0,它仍会补偿不必要的计数器.
The second part however is what I seem to be having problems with. userQuantity[] is an int array and it has to be an array. This does not seem to do anything to the code. Even if 0 is entered for the quantity, it still incrememnts the counter which is not desireable.
为了避免混淆,我应该解释这是一个无限的for循环(带有break语句).我执行for循环的原因是因为我必须这样做.是因为我的for循环条件不起作用,还是我做错了什么?
这是我的大学作业,因此我希望获得带说明的答案,而不仅仅是快速解决方案.如果您需要我解释,请告诉我.
This is for my college assignment so I would appreciate answers with explanation and not just quick-fixes. If you need me to explain, let me know please.
推荐答案
尽管在Java中并非严格违法,但从循环内部更改for循环控制变量的值并不是一个好主意.(这种修改 在其他一些语言中是非法的.)
Although it's not strictly illegal in Java, it's not a good idea to change the value of the for loop control variable from within the loop. (Such modification is illegal in some other languages.)
通过更改循环中的循环迭代变量,您会弄乱使用 for
循环所提供的隐式假设.例如,如果读者看到以下内容:
By changing the loop iteration variable within the loop, you're messing with the implicit assumptions offered by your use of a for
loop. For example, if a reader sees:
for (int i = 0; i < 10; i++) {
// ...
}
读者将正确地认为循环旨在执行10次(如果其中有 break
,则循环不超过10次).但是,如果您要在循环中更改 i
的值,则该假设不再有效.
the reader will rightfully assume that the loop is intended to execute exactly 10 times (or, no more than 10 if there is a break
in there). However, if you go changing the value of i
within the loop, this assumption is no longer valid.
如果必须更改计数器的值,我建议将其写为 while
循环:
If you must change the value of the counter, I would suggest writing this as a while
loop instead:
int i = 0;
while (i < 10) {
// ...
i++;
}
以及一条注释,解释了为什么要在循环中更改 i
以及这样做的含义.
along with a comment that explains why you are changing i
within the loop and what it means to do so.
这篇关于Java-根据条件将for循环计数器调回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!