(另一个)“非静态方法不能从静态上下文引用”问题

时间:2013-02-10 16:03:38

标签: java call static-methods non-static main-method

错误:无法从静态上下文引用非静态方法。

在我的例子中,该方法称为readFile()。

您好。我遇到了无数新手程序员之前遇到的同样的错误,但是尽管已经连续几个小时阅读了它,但我无法弄清楚如何在我的情况下应用这些知识。

我认为代码可能需要重新构建,所以我要包含该类的全文。

我更喜欢在main Main类中包含main()方法,但为了简单起见,将它放在同一个类中。无论我把它放在哪里,我都会得到同样的错误。

readFile()方法可以很容易地放在main()方法中,但我更愿意学习如何创建这样的小模块化方法,并从main()方法调用它们。 最初closeFile()也是一个单独的方法。

该计划应该:

  1. 打开.dat文件
  2. 从有关考试结果的文件数据中读入
  3. 对信息进行计算
  4. 输出计算结果
  5. 文件的每一行都是关于个别学生的信息 一份由三份试卷组成 大多数计算都考虑到了个别学生 但是有些计算考虑了整个学生集合(即他们的班级)。

    NB:在代码中使用单词“class”,它指的是学生的学术课程,而不是OO编程意义上的课程。

    我尝试了各种解决问题的方法。

    目前的方法是在“考试”课程的实例中容纳有关单个学生考试的数据 这对应于输入文件的单行,以及仅关于该实例的其他属性的后续计算。

    这些属性在readFile()的while循环期间填充了值 当while循环结束时,将调用涉及整个考试集合(即整个学术课程)的三个计算。

    第二个问题是:
    在评论“声明属性”下,我将类的属性分为两个子组:
    那些我认为应该被定义为类变量(使用关键字static) 我认为那些应该被定义为实例变量 你能否指导我是否应该向第一组中的人添加关键字static。

    相关问题是:
    使用整个实例集合执行计算的方法是否也应声明为静态/类方法? 当我尝试这样做时,我在尝试调用实例方法时遇到了类似的错误。

    感谢。

    PS:关于这个论坛:
    我用代码块包含了代码,但没有突出显示Java语法 也许在我提交帖子后它会改变。 但如果不是,如果有人能告诉我如何,我会很乐意重新格式化。

    PPS:这是一项家庭作业 我已经在下面创建了所有代码 “家庭作业”标签已经过时,所以我没有使用它。


    输入文件名:“results.dat”
    输入文件路径:“C:/ Users / ADMIN / Desktop / A1P3E1 Files / results.dat”
    输入文件内容(随机生成的数据):

    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文件名:“Exam.java”
    Java包名称:“a1p3e1”
    Java项目名称:“A1P3E1”
    Java文件内容:

    /** 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
    

1 个答案:

答案 0 :(得分:3)

readFile是一种实例方法。创建要使用的Exam实例:

new Exam().readFile();

鉴于Exam有许多实例变量,其中一些在readFile方法中使用,因此该方法不应该是静态的。 (使用static类变量会产生代码气味,不应考虑。)

鉴于readFile从文件中读取多个条目到多个Exam对象,您可以将读取功能拆分为新的ExamReader类。

旁白:为了灵活使用List而不是固定大小的数组

Exam exam [];

可能是

List<Exam> examList;