简体   繁体   中英

non-static variable x cannot be referenced from a static context

Excuse my ignorance. I'm a beginner:

Why is the following code giving me the following compiling error? [line: 16] non-static variable x cannot be referenced from a static context

public class average{
int [] numbers = {2,3,4,5,6};
double x = averageMark(numbers);

public static double averageMark(int [] numbers){
    int sum = 0;  
    double average = 0.000;
    for (int i = 0; i < numbers.length; i++){  
      sum = numbers [i] + sum;  
      average = sum/numbers.length;  
    }
    return average;
  }

  public static void main (String [] args){
  System.out.println(x);
  }
}

The error says it all

non-static variable x cannot be referenced from a static context

you have to either make it x static variable.

static double x = averageMark(numbers);

or create an instance of Average and access it.

 public static void main (String [] args){
   System.out.println(new Average().x);
  }

Btw, its a convention that your class names should start with Uppercase.

as @ mgaert noted you need to make numbers array static as well, cuz you use it in a static method.

static int [] numbers = {2,3,4,5,6};

Static method or a variable is not attached to a particular object, but rather to the class as a whole. They are allocated when the class is loaded. If you try to use an instance variable from inside a static method, the compiler thinks, “I don't know which object's instance variable you're talking about!” But if you'll create new instance of average class, you'll be able to access it through this instance, so modify it like this:

public class average{
public int [] numbers = {2,3,4,5,6};
public double x;   
public static double averageMark(int [] numbers){
    int sum = 0;  
    double average = 0.000;
    for (int i = 0; i < numbers.length; i++){  
      sum = numbers [i] + sum;  
      average = sum/numbers.length;  
    }
    return average;
  }

  public static void main (String [] args){
  average a = new average(); // creating new instance 'a'
  a.x = average.averageMark(a.numbers); // assigning to variable 'x' of instance 'a' result of averageMark
  System.out.println(a.x); // output a
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM