Blackvein
Blackvein

Reputation: 558

Java: perform for statement until given variable has reached a certain value?

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

Answers (4)

user207421
user207421

Reputation: 310980

Surely it is the do/while loop that isn't terminating? That for loop cannot possibly run forever.

Upvotes: 0

srkavin
srkavin

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

NPE
NPE

Reputation: 500663

There are several possibilities:

  1. you change variable inside the body of the loop;
  2. you change other_variable inside the body of the loop;
  3. other_variable is set to a large value, in which case the loop might take a long time to terminate;
  4. your code never completes a certain iteration of the loop, for example:
    • it's getting stuck inside a nested loop as suggested by @Eng.Fouad in the comments, or
    • it's waiting for a lock, or
    • it's blocking inside an I/O call that never completes (or takes a long time to complete) etc.

Without knowing the typical value of other_variable and seeing the body of the loop it's anyone's guess.

Upvotes: 4

r0ast3d
r0ast3d

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

Related Questions