Forum Stats

  • 3,874,184 Users
  • 2,266,680 Discussions
  • 7,911,761 Comments

Discussions

Cannot Reference a non static field from a static context error

User_KIJWJ
User_KIJWJ Member Posts: 1 Green Ribbon

/**

 * practice

 */

public class Practice {


   public int[] myArray = {1,2,3,4,5,6};  


public void sumAndProduct(int [] arr){

int sum = 0;

int product = 1;

    for(int i = 0; i < myArray.length; i++){

        sum += myArray[i];

        product  *= myArray[i];

    }

System.out.println("The sum is: " + sum);

System.out.println("The product is: " + product);

}



public static void main(String[] args) {

    Practice demo = new Practice();

    demo.sumAndProduct(myArray);

   

}


}

Tagged:

Answers

  • justsomeone
    justsomeone Member Posts: 38 Red Ribbon
    edited Oct 21, 2022 12:20PM

    main method is static so it can not access any instance member and myArray is an instance field so to access it

    based in your use case you have 2 option


    1) demo.sumAndProduct(demo.myArray);

    or

    2) change the signature of this method

    public void sumAndProduct(int [] arr) to

    public void sumAndProduct() as i see you did not used the arr parameter and you used myArray in your code


    hope that help and have a nice day :)

  • justsomeone
    justsomeone Member Posts: 38 Red Ribbon

    another option

    is to change  myArray to be static field

    so this

     public int[] myArray = {1,2,3,4,5,6}; 

    be

     public static int[] myArray = {1,2,3,4,5,6}; 


    but second option from my first replay would be better as you never used the arr parameter

    and have a nice day :)