i know i'm now loosing the plot over this so any rapid help will be appreciated!

i have to write a method which calculates the average from numbers contained in a list, when i try and run the code i get the error message:

Semantic error: Cannot reach instance method: average( java.util.List ) from static context: Student

the code for the average() method is:

    * calculates the average
   public int average(List<Integer> userData)
      int total = 0;
      for (int eachElement : userData)
         total = total + eachElement;
      int avg = ((int)total) / userData.size();
      System.out.println("average = " + avg);
      return avg;

i've been given the following two lines to test this works

Integer[] numberArray = {75, 59, 0, 70};

but when i try to execute these two lines in my test enviroment i get the error message??


Recommended Answers

All 4 Replies

Student is a class, that method is meant to be called using an instance, and not a class, reference. So, either create an instance of Student and call the method using that, or declare the method static.

Either way will work, since that method is not using any instance data, itself.

so if i wanted it to use the instance data what would i change? i should be sending data values (a list of int) to this method and then returning avg, the average of the list.

adatapost>masijade has explained and I am giving an example.

Integer[] numberArray = {75, 59, 0, 70};

Student s=new Student();  // Create an Instance of Student class

so the only reason this didn't work is because i hadn't created a Student object in the workspace! doh!!

thanks for the help, i'm sure there'll be more later!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.