Search code examples
javaarraysfor-looplocal-variablesprivate-methods

Variable in for loop is giving a message that "The value of the local variable i is not used"


I wrote a for loop that is supposed to determine if there is user input. If there is, it sets the 6 elements of int[] valueArr to the input, a vararg int[] statValue. If there is no input, it sets all elements equal to -1.

if (statValue.length == 6) {
    for (int i = 0; i < 6; i++) {
        valueArr[i] = statValue[i];
    }

} else {
    for (int i : valueArr) {
        i = -1;
    }
}

I am using Visual Studio Code, and it is giving me a message in for (int i : valueArr) :

"The value of the local variable i is not used."

That particular for loop syntax is still new to me, so I may be very well blind, but it was working in another file:

for(int i : rollResults) {
    sum = sum + i;
}

I feel that I should also mention that the for loop giving me trouble is in a private void method. I'm still fairly new and just recently started using private methods. I noticed the method would give the same message when not used elsewhere, but I do not see why it would appear here.

I tried closing and reopening Visual Studio Code, deleting and retyping the code, and other forms of that. In my short experience, I've had times where I received errors and messages that should not be there and fixed them with what I mentioned, but none of that worked here.


Solution

  • for (int i : valueArr) {
     .... CODE HERE ...
    }
    

    This sets up a loop which will run CODE HERE a certain number of times. Inside this loop, at the start of every loop, an entirely new variable is created named i, containing one of the values in valueArr. Once the loop ends this variable is destroyed. Notably, i is not directly the value in valueArr - modifying it does nothing - other than affect this one loop if you use i later in within the block. It does not modify the contents of valueArr.

    Hence why you get the warning: i = -1 does nothing - you change what i is, and then the loop ends, which means i goes away and your code hasn't changed anything or done anything, which surely you didn't intend. Hence, warning.

    It's not entirely clear what you want to do here. If you intend to set all values in valueArr to -1, you want:

    for (int i = 0; i < valueArr.length; i++) valueArr[i] = -1;
    

    Or, actually, you can do that more simply:

    Arrays.fill(valueArr, -1);
    

    valueArr[i] = -1 changes the value of the i-th value in the valueArr array to -1. for (int i : valueArr) i = -1; does nothing.