Search code examples
javaloopsfor-loopwhile-loopnested-loops

Store dynamic int value in local variable to static?


Okay so I ran into a little problem and I'm not entirely sure how to word the question properly so the title may be a little misleading. Also, the code I'm having trouble with is a small part of a larger one, so I'll do my best to explain my situation.

Basically, this piece of code is in a for loop and what I'm trying to make it do is to make a certain variable decrement by a certain number each time the loop runs.

int column = h - 1;

if (array[i] == 1)
{
   while (d < column - 1)
   {
      r.lower();
      d++
   }
   if (d == column - 1)
   {
      r.drop();
      column -=1;
   }
}

Sorry if it looks a bit cryptic. Just forget about the d and r variables for now and focus on the column and h.

What I'm trying to make it do is take the value of the height minus one (h - 1) and store it in the local variable column, and then decrement it by 1 (column -= 1)so the value will be updated for the next time the loop runs and the IF statement conditions are fulfilled.

The problem here is that the height is a dynamic variable - throughout the rest of the code it is constantly changing and because of that, my code will only work the first time and when it runs a second time, it doesn't seem to decrement at all.

So my question is: how can I store the CURRENT value of the height into a local variable, and make it static (keeps the same value throughout the loop) so that I can successfully decrement it?

Sorry if that was poorly explained and please correct me if I am using any terms wrongly.

Thanks for your time!


Solution

  • Might have to do an edit or two if I misunderstood the question, but here's what I got based on my initial understanding.

    What this does is only takes the value of h for the for loop the first time it goes through. At the end of the first time (and all times through), it saves the value to a global variable. In subsequent iterations, that saved value is retrieved and used again instead of h.

    have a global variable isFirstTimeThroughLoop or the like, set to true, and a global int or what have you called lastValueOfHeight or whatever, not initialized.

    Within the loop...

    int tempHeight;
    if(isFirstTimeThroughLoop)
    {
        tempHeight = h; //your value of h
        isFirstTimeThroughLoop = false;
    }
    else
    {
        tempHeight = lastValueOfHeight;
    }
    

    then at the end of your loop, make sure to store the value of tempHeight back to lastValueOfHeight

    lastValueOfHeight = tempHeight;
    

    let me know if I misunderstood anything so I can help out more!