Note that there are some explanatory texts on larger screens.

plurals
  1. POVariable Assignment and loops
    text
    copied!<p>A while back, I was working on a program that hashed values into a hashtable (I don't remember the specifics, and the specifics themselves are irrelevant to the question at hand). Anyway, I had the following code as part of a "recordInput" method:</p> <pre><code>tempElement = new hashElement(someInt); while(in.hasNext() == true) { int firstVal = in.nextInt(); if (firstVal == -911) { break; } tempElement.setKeyValue(firstVal, 0); for(int i = 1; i&lt;numKeyValues;i++) { tempElement.setKeyValue(in.nextInt(), i); } elementArray[placeValue] = tempElement; placeValue++; } // close while loop } // close method </code></pre> <p>This part of the code was giving me a very nasty bug -- no matter how I finagled it, no matter what input I gave the program, it would always produce an array full of only a single value -- the last one. </p> <p>The problem, as I later determined it, was that because I had not created the tempElement variable within the loop, and because values were not being assigned to <code>elementArray[]</code> until after the loop had ended -- every term was defined rather as "tempElement" -- when the loop terminated, every slot in the array was filled with the last value tempElement had taken.</p> <p>I was able to fix this bug by moving the declaration of tempElement within the while loop. My question to you, Stackoverflow, is whether there is another (read: better) way to avoid this bug while keeping the variable declaration of tempElement outside the while loop.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload