0

ERROR: non-static method cannot be referenced from a static context.

In my case the method is called readFile().

Hi. I'm experiencing the same error that countless novice programmers have before, but despite reading about it for hours on end, I can't work out how to apply that knowledge in my situation.

I think the code may need to be restructured so I am including the full text of the class.

I would prefer to house the main() method in small Main class, but have placed it in the same class here for simplicity. I get the same error no matter where I put it.

The readFile() method could easily be placed within the main() method, but I’d prefer to learn how to create small modular methods like this and call them from a main() method. Originally closeFile() was a separate method too.

The program is supposed to:

  1. open a .dat file
  2. read in from the file data regarding examination results
  3. perform calculations on the information
  4. output the results of the calculations

Each line of the file is information about an individual student.
A single consists of three examination papers.
Most calculations regard individual students.
But some calculations regard the entire collection of students (ie their class).

NB: where the word “class” is used in the code, it refers to academic class of the students, not class in the sense of OO programming.

I have tried various ways to solve problem.

Current approach is to house data concerning a single student examination in an instance of the class “Exam”.
This corresponds to a single line of the input file, plus subsequent calculations concerning other attributes of that instance only.

These attributes are populated with values during the while loop of readFile().
When the while loop ends, the three calculations that concern the entire collection of Exams (ie the entire academic class) are called.

A secondary question is:
Under the comment “Declare Attributes”, I’ve separated the attributes of the class into two subgroups:
Those that I think should be defined as class variables (with keyword static).
Those that I think should be defined as instance variables.
Could you guide me on whether I should add keyword static to those in first group.

A related question is:
Should the methods that perform calculations using the entire collection of instances be declared as static / class methods too?
When I tried that I then got similar errors when these tried to call instance methods.

Thanks.

PS: Regarding this forum:
I have enclosed the code with code blocks, but the Java syntax is not highlighted.
Perhaps it will change after I submit the post. But if not I'd be happy to reformat it if someone can tell me how.

PPS: this is a homework assignment.
I have created all the code below myself.
The "homework" tag is obsolete, so I didn't use it.


Input File Name: "results.dat"
Input File Path: "C:/Users/ADMIN/Desktop/A1P3E1 Files/results.dat"
Input File Contents (randomly generated data):

573,Kalia,Lindsay,2,8,10
966,Cheryl,Sellers,8,5,3
714,Shea,Wells,7,6,2
206,April,Mullins,8,2,1
240,Buffy,Padilla,3,5,2
709,Yoko,Noel,3,2,5
151,Armand,Morgan,10,9,2
199,Kristen,Workman,2,3,6
321,Iona,Maynard,10,2,8
031,Christen,Short,7,5,3
863,Cameron,Decker,6,4,4
986,Kieran,Harvey,7,6,3
768,Oliver,Rowland,8,9,1
273,Clare,Jacobs,9,2,7
556,Chaim,Sparks,4,9,4
651,Paloma,Hurley,9,3,9
212,Desiree,Hendrix,7,9,10
850,McKenzie,Neal,7,5,6
681,Myra,Ramirez,2,6,10
815,Basil,Bright,7,5,10

Java File Name: "Exam.java"
Java Package Name: "a1p3e1"
Java Project Name: "A1P3E1"
Java File Contents:

/** TODO
 *  [+] Error Block - Add Finally statement
 *  [?] studentNumber - change data type to integer (or keep as string)
 *  [?] Change Scope of to Non-Instance Variables to Static (eg classExamGradeSum)
 *  [*] Solve "non-static method cannot be referenced from a static context" error
 *
 */

package a1p3e1; // Assignment 1 - Part 3 - Exercise 1

import java.io.*;
import java.util.*;

/**
 *
 * @author                                                                           
 */

public class Exam {

//  (1) Declare Attributes
//  (-) Class Attributes
    protected Scanner fileIn;
    protected Scanner lineIn;
    private String line;
    private String [] splitLine;

    private String InFilePath = "C:/Users/ADMIN/Desktop/A1P3E1 Files/results.dat";
    private int fileInRowCount = 20;
    private int fileInColumnCount = 6;
    private int fileOutRowCount = 20;
    private int fileOutColumnCount = 14;

//    private int classExamGradeSum = 0;                                             
    private int classExamGradeSum;
    private double classExamGradeAverage = 0.0;
    private int [] classExamGradeFrequency = new int [10];                           

    protected Exam exam []  = new Exam [fileInRowCount];                             


//  (-) Instance Attributes
    private String studentNumber;                                                    
    private String forename;
    private String surname;
    private int paper1Grade;
    private int paper2Grade;
    private int paper3Grade;

    private String paper1Outcome;
    private String paper2Outcome;
    private String paper3Outcome;

    private int fileInRowID;
    private int failCount;
    private int gradeAverageRounded;
    private int gradeAverageQualified;
    private String examOutcome;


//  (3) toString Method Overridden
    @Override
    public String toString () {
        return    "\n Student Number:       " + studentNumber
                + "\n Forename:             " + forename
                + "\n Surname:              " + surname
                + "\n Paper 1 Grade:        " + paper1Grade
                + "\n Paper 2 Grade:        " + paper2Grade
                + "\n Paper 3 Grade:        " + paper3Grade
                + "\n Paper 1 Outcome:      " + paper1Outcome
                + "\n Paper 2 Outcome:      " + paper2Outcome
                + "\n Paper 3 Outcome:      " + paper3Outcome
                + "\n File In Row ID:       " + fileInRowID
                + "\n Fail Count:           " + failCount
                + "\n Exam Grade Rounded:   " + gradeAverageRounded
                + "\n Exam Grade Qualified: " + gradeAverageQualified
                + "\n Exam Outcome:         " + examOutcome;
    }


//  (4) Accessor Methods
    public String getStudentNumber () {
        return studentNumber;
    }

    public String getForename () {
        return forename;
    }

    public String getSurname () {
        return surname;
    }

    public int getPaper1Grade () {
        return paper1Grade;
    }

    public int getPaper2Grade () {
        return paper2Grade;
    }

    public int getPaper3Grade () {
        return paper3Grade;
    }

    public String getPaper1Outcome () {
        return paper1Outcome;
    }

    public String getPaper2Outcome () {
        return paper2Outcome;
    }

    public String getPaper3Outcome () {
        return paper3Outcome;
    }

    public int getFileInRowID () {
        return fileInRowID;
    }

    public int getFailCount () {
        return failCount;
    }

    public int getGradeAverageRounded () {
        return gradeAverageRounded;
    }

    public int getGradeAverageQualified () {
        return gradeAverageQualified;
    }

    public String getExamOutcome () {
        return examOutcome;
    }


//  (5) Mutator Methods

    public void setStudentNumber (String studentNumber) {
        this.studentNumber = studentNumber;
    }

    public void setForename (String forename) {
        this.forename = forename;
    }

    public void setSurname (String surname) {
        this.surname = surname;
    }

    public void setPaper1Grade (int paper1Grade) {
        this.paper1Grade = paper1Grade;
    }

    public void setPaper2Grade (int paper2Grade) {
        this.paper2Grade = paper2Grade;
    }

    public void setPaper3Grade (int paper3Grade) {
        this.paper3Grade = paper3Grade;
    }

    public void setPaper1Outcome (String paper1Outcome) {
        this.paper1Outcome = paper1Outcome;
    }

    public void setPaper2Outcome (String paper2Outcome) {
        this.paper2Outcome = paper2Outcome;
    }

    public void setPaper3Outcome (String paper3Outcome) {
        this.paper3Outcome = paper3Outcome;
    }

    public void setFileInRowID (int fileInRowID) {
        this.fileInRowID = fileInRowID;
    }

    public void setFailCount (int failCount) {
        this.failCount = failCount;
    }

    public void setGradeAverageRounded (int gradeAverageRounded) {
        this.gradeAverageRounded = gradeAverageRounded;
    }

    public void setGradeAverageQualified (int gradeAverageQualified) {
        this.gradeAverageQualified = gradeAverageQualified;
    }

    public void setExamOutcome (String examOutcome) {
        this.examOutcome = examOutcome;
    }


//  (2) Constructor Methods
//  (-) Constructor Method - No Arguments
    public Exam () {
        this.studentNumber = "";
        this.forename = "";
        this.surname = "";
        this.paper1Grade = 0;
        this.paper2Grade = 0;
        this.paper3Grade = 0;
        this.paper1Outcome = "";
        this.paper2Outcome = "";
        this.paper3Outcome = "";
        this.fileInRowID = 0;
        this.failCount = 0;
        this.gradeAverageRounded = 0;
        this.gradeAverageQualified = 0;
        this.examOutcome = "";
    }

//  (-) Constructor Method - With Arguments (1)
    public Exam (
            String studentNumber,
            String forename,
            String surname,
            int paper1Grade,
            int paper2Grade,
            int paper3Grade,
            String paper1Outcome,
            String paper2Outcome,
            String paper3Outcome,
            int fileInRowID,
            int failCount,
            int gradeAverageRounded,
            int gradeAverageQualified,
            String examOutcome) {
        this.studentNumber = studentNumber;
        this.forename = forename;
        this.surname = surname;
        this.paper1Grade = paper1Grade;
        this.paper2Grade = paper2Grade;
        this.paper3Grade = paper3Grade;
        this.paper1Outcome = paper1Outcome;
        this.paper2Outcome = paper2Outcome;
        this.paper3Outcome = paper3Outcome;
        this.fileInRowID = fileInRowID;
        this.failCount = failCount;
        this.gradeAverageRounded = gradeAverageRounded;
        this.gradeAverageQualified = gradeAverageQualified;
        this.examOutcome = examOutcome;
    }

//  (-) Constructor Method - With Arguments (2)                                      
    public Exam (
            String studentNumber,
            String forename,
            String surname,
            int paper1Grade,
            int paper2Grade,
            int paper3Grade) {
        this.studentNumber = studentNumber;
        this.forename = forename;
        this.surname = surname;
        this.paper1Grade = paper1Grade;
        this.paper2Grade = paper2Grade;
        this.paper3Grade = paper3Grade;
        this.paper1Outcome = "";
        this.paper2Outcome = "";
        this.paper3Outcome = "";
        this.fileInRowID = 0;
        this.failCount = 0;
        this.gradeAverageRounded = 0;
        this.gradeAverageQualified = 0;
        this.examOutcome = "";
    }


//  (6) Main Method
    public static void main (String[] args) throws Exception {

        Exam.readFile ();                                                            
    }


//  (7) Other Methods

//  (-) Read File Into Instances Of Exam Class
    //  limitation: hard coded to 6 column source file
    public void readFile () throws Exception {

        try {                                                                        

            fileIn = new Scanner(new BufferedReader(new FileReader(InFilePath)));

        int i = 0;

        while (fileIn.hasNextLine ()) {                                              

            line = fileIn.nextLine();

            splitLine = line.split (",", 6);

            //  create instances of exam from file data and calculated data
            exam [i] = new Exam (
                    splitLine [0],
                    splitLine [1],
                    splitLine [2],
                    Integer.parseInt (splitLine [3]),
                    Integer.parseInt (splitLine [4]),
                    Integer.parseInt (splitLine [5]),
                    convertGradeToOutcome (paper1Grade),
                    convertGradeToOutcome (paper2Grade),
                    convertGradeToOutcome (paper3Grade),
                    i + 1,
                    failCount (),
                    gradeAverageRounded (),
                    gradeAverageQualified (),
                    convertGradeToOutcome (gradeAverageQualified));

            fileIn.nextLine ();                                                      
            i ++;
        }

        classExamGradeFrequency ();
        classExamGradeSum ();
        classExamGradeAverage ();

        //  close file                                                               
        fileIn.close ();

        } catch (FileNotFoundException | NumberFormatException e) {

//            fileIn.next ();                                                        
            System.err.println("Error: " + e.getMessage());
            //System.out.println ("File Error - IO Exception");
        }

        for (Exam i : exam) {
            System.out.println(i.toString());
            System.out.println();
        }

//        System.out.println(classExamGradeSum);
//        System.out.println();
        System.out.println(classExamGradeAverage);
        System.out.println();
        System.out.println(classExamGradeFrequency);
        System.out.println();

    }


//  (-) Fail Count (1 Student, 3 Papers)
    public int failCount () {
//
        if (paper1Grade > 6){
            failCount = failCount + 1;
        }
        if (paper2Grade > 6){
            failCount = failCount + 1;
        }
        if (paper3Grade > 6){
            failCount = failCount + 1;
        }
        return failCount;
    }


//  (-) Grade Average Rounded (1 Student, 3 Papers)
    public int gradeAverageRounded () {

        gradeAverageRounded = (int) Math.ceil(
            (paper1Grade + paper2Grade + paper3Grade) / 3);

        return gradeAverageRounded;
    }


//  (-) Grade Average Qualified (1 Student, 3 Papers)
    public int gradeAverageQualified (){

        gradeAverageQualified = gradeAverageRounded;                                 

        if (failCount >= 2 && gradeAverageRounded <= 6) {
            gradeAverageQualified = 7;
        }

        return gradeAverageQualified;
    }


//  (-) Convert Grade to Outcome (Pass / Fail)
    public String convertGradeToOutcome (int grade) {
        String outcome;

        if (grade <= 6){
            outcome = "Pass";
        } else if (grade > 6){
            outcome = "Fail";
        } else {
            outcome = "Unknown (Error)";
        }

        return outcome;
    }


//  (-) Class Exam Grade Sum (All Students, All Papers)
    /** assumption: average grade for class is average of grades awarded,
     *  using rounded figures, not raw per paper results
     */
    public void classExamGradeSum () {

        classExamGradeSum = 0;

        //  for each loop (to iterate through collection of exam instances)
        for (Exam i : exam) {
            classExamGradeSum = classExamGradeSum + i.gradeAverageQualified;
        }
    }


//  (-) Class Exam Grade Average (All Students, All Papers)
    /** assumption: average grade for class is average of grades awarded,
     *  using rounded figures, not raw per paper results
     *  assumption: <fileInRowCount> is correct                                      
     */
    public double classExamGradeAverage () {

        classExamGradeAverage = classExamGradeSum / fileInRowCount;

        return classExamGradeAverage;
    }


//  (-) Class Exam Grade Frequency (Count of Instances of Each Final Grade)
    /** Example:
     *  frequency of average grade "5"
     *  is stored in array <classExamGradeFrequency [4]>
     */
    public void classExamGradeFrequency () {

        //  for each loop (to iterate through collection of exam instances)
        for (Exam i : exam) {
            classExamGradeFrequency [i.getGradeAverageQualified () - 1] ++;
        }
    }


}// endof class
4

1 回答 1

3

readFile is an instance method. Create an instance of Exam to use:

new Exam().readFile();

Given that the Exam has many instance variables, some of which are used in the readFile method, this method should not be static. (Use of static class variables creates code smell and should not be considered.)

Given that readFile reads multiple entries from the file into many Exam objects, you could split out the read functionality into a new ExamReader class.

Aside: For flexibility use a List instead of a fixed size array

Exam exam [];

could be

List<Exam> examList; 
于 2013-02-10T16:06:13.533 回答