When I pass the array "bucky" to the change function and in the change function if I use an enhanced for loop, the variable counter gives the error "The value of the local variable counter is not used"
But if I put the body of the for loop in an System.out.println(counter =5)
the error does not appear
class apples{
public static void main(String[] args) {
int bucky[]={3,4,5,6,7};
change(bucky);
}
public static void change(int x[]){
for(int counter: x){
counter =5;
}
}
}
Why does this code give the error I mentioned above since I'm using the counter variable in the enhanced for loop?
Edit - my objective is to change values of the array inside the "change" function and return it back to main.
CodePudding user response:
Question is about updating original array values, then you have to use normal for loop so that each index values can be updated:
class apples{
public static void main(String[] args) {
int bucky[]={3,4,5,6,7};
bucky = change(bucky);
for(int b:bucky) {
System.out.println(b);
}
}
public static void change(int x[]){
for (int i = 0; i < x.length; i ) {
x[i]=x[i] 5;
}
return x;
}
}