sixtytrees
sixtytrees

Reputation: 1233

Minimizing the scope of a variable in do ... while loop [Java] - ERROR: Symbol cannot be found

I would like to minimize the scope of arr to a do ... while loop, so it can be destroyed once the loop is exited.

If I declare arr within the do while loop, I get the error:

symbol cannot be found

I can declare it right before the cycle, but then I keep bloated arr in memory even though I don't need it any more.

//int[] arr = {0}; // this works, but the scope is outside the loop
do {
    int[] arr = {0};  // causes "cannot find symbol" on `while` line
    arr = evolve(arr); // modifies array, saves relevant results elsewhere
    } while (arr.length < 9999);

What is the correct way to deal with this situation?

Upvotes: 4

Views: 191

Answers (5)

Hulk
Hulk

Reputation: 6573

Yet another option - although arguably not better than any of those already mentioned - would be to wrap it into a block:

{
    int[] arr = {0}; // this works, but the scope is outside the loop
    do {
        int[] arr = {0};
        arr = evolve(arr); // modifies array, saves relevant results elsewhere
    } while (arr.length < 9999);
}

I'd prefer @martinhh's solution though - just extract it to a method with a meaningful name.

The body-less for loop is fine, too - but it would probably be a good idea to leave a comment there that it was indeed intentional to omit the body - things like that tend to get highlighted by static analysis tools and may cause some confusion.

Upvotes: 1

martinhh
martinhh

Reputation: 346

You could also define the array outside the do-while loop and wrap the whole thing in a small method. The array will then be garbage collected when the method ends. This also helps to structure your code.

Upvotes: 2

Bohemian
Bohemian

Reputation: 425053

You have:

  • An initial state
  • A terminating state
  • An iterative operation

So you have everything needed to use a for loop (albeit without a body):

for (int[] arr = {0}; arr.length < 9999; arr = evolve(arr));

Another solution, but nowhere near as neat, is to add this after the loop:

arr = null;

which still allows the allocated memory to be garbage collected and has a similar practical effect to restricting scope. Sometimes you need this approach if you can't refactor the code another way.

Upvotes: 6

JavaHopper
JavaHopper

Reputation: 5607

@Bohemian's solution is elegant.

But, if you still wan't to achieve this using do.. while, then following solution should work

    int l = 9999;
    do {
        int[] arr = { 0 }; // causes "cannot find symbol" on `while` line
        arr = evolve(arr); // modifies array, saves relevant results elsewhere
        l = arr.length;
    } while (l < 9999);

Upvotes: 2

user6679234
user6679234

Reputation:

You have a couple of ways. You can declare boolean token outside of a cicle and check against it. You can encapsulate the whole thing in a method that ends right after do while.

Upvotes: 2

Related Questions