Reputation: 558
I want to have a for
statement that repeats until a given int
reaches a certain value.
For example...
for (int variable = 0; variable < other_variable; variable++) {
The problem with this is that the for
statement will never end. It will continue to repeat endlessly. What have I done wrong?
This is my code...
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);
In this code, m_area.m_items.size()
would return 1
, so i2
would be 1
.
Upvotes: 1
Views: 1935
Reputation: 310980
Surely it is the do/while
loop that isn't terminating? That for
loop cannot possibly run forever.
Upvotes: 0
Reputation: 1180
On a side note,
String s2 = m_area.m_items.get(i).returnName();
is going to cause an exception if invoked in a subsequent or later repetition after
m_area.m_items.remove(i);
is invoked, because every time m_area.m_items.remove(i)
is invoked, the list/array loses an item and its size reduces, which is never reflected in the iteration boundary check.
Upvotes: 0
Reputation: 500663
There are several possibilities:
variable
inside the body of the loop;other_variable
inside the body of the loop;other_variable
is set to a large value, in which case the loop might take a long time to terminate;Without knowing the typical value of other_variable
and seeing the body of the loop it's anyone's guess.
Upvotes: 4
Reputation: 2635
You should try a
do {
}while(condition is true)
loop. However that said, you have to implement checks assuming that there will be runaway data or conditions resulting in an infinite loop. Just my 2 cents
Upvotes: -1