Variable Assignment and loops (Java)

Posted by Raven Dreamer on Stack Overflow See other posts from Stack Overflow or by Raven Dreamer
Published on 2010-06-07T15:25:47Z Indexed on 2010/06/07 15:32 UTC
Read the original article Hit count: 332

Greetings Stack Overflowers,

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.

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<numKeyValues;i++)
        {
            tempElement.setKeyValue(in.nextInt(), i);
        }

        elementArray[placeValue] = tempElement;
        placeValue++;

    }   // close while loop

} // close method

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.

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 elementArray[] 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.

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.

(suggestions for better title and tags also appreciated)

© Stack Overflow or respective owner

Related posts about java

Related posts about loops