[英]Java: perform for statement until given variable has reached a certain value?
我希望有一个for
语句重复,直到给定的int
达到某个值。
例如...
for (int variable = 0; variable < other_variable; variable++) {
问题是for
语句永远不会结束。 它会不断重复不断。 我做错了什么?
这是我的代码......
boolean itemexist_check = false;
do {
int i2 = m_area.m_items.size();
for (int i = 0; i < i2; i++) {
String s2 = m_area.m_items.get(i).returnName();
System.out.println("Checking...");
if (s2.contains(s)) {
System.out.println("You take the " + s2 + ".");
itemexist_check = true;
player.addItem(m_area.m_items.get(i));
m_area.m_items.remove(i);
}
else {
//do nothing, repeat loop
}
}
}
while (itemexist_check == false);
在此代码中, m_area.m_items.size()
将返回1
,因此i2
将为1
。
有几种可能性:
variable
; other_variable
; other_variable
设置为一个较大的值,在这种情况下,循环可能需要很长时间才能终止; 在不知道other_variable
的典型值并且看到循环体的情况下,这是任何人的猜测。
在旁注,
String s2 = m_area.m_items.get(i).returnName();
如果在之后的后续或后续重复中调用,将导致异常
m_area.m_items.remove(ⅰ);
会被调用,因为每次调用m_area.m_items.remove(i)
,列表/数组都会丢失一个项目,并且其大小会减小,这从没有体现在迭代边界检查中。
当然, do/while
循环不会终止吗? 该for
循环不可能永远运行。
你应该尝试一下
do {
}while(condition is true)
环。 无论如何,你必须实现检查,假设会有失控的数据或条件导致无限循环。 只需2美分
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.