Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing array to a function and using that array in an Enhanced for loop

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Edit – my objective is to change values of the array inside the "change" function and return it back to main.

>Solution :

The variable counter is not used. Yes, you use it in the loop but you’re not returning it or utilizing its value for other operations.

If you put it inside a System.out.println then you are using it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading