(另一个)“不能从静态上下文引用非静态方法”。问题 [英] (Another) "non-static method cannot be referenced from a static context" issue

查看:95
本文介绍了(另一个)“不能从静态上下文引用非静态方法”。问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

在我的情况下,该方法称为readFile()。

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.

我希望将main()方法放在小的Main类,但为了简单起见,将其放在同一类中。无论放在哪里,我都会遇到相同的错误。

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.

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

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.

该程序应该:


  1. 打开一个.dat文件

  2. 从文件数据中读取与检查结果有关的数据

  3. 对信息进行计算

  4. 输出计算结果

  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.

这些属性在readFile()的while循环期间填充值。

当while循环结束时,将调用涉及整个考试集合(即整个学术班级)的三个计算。

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第二个问题是:

在注释声明属性下,我将类的属性分为两个子组:

我认为应该将其定义为类变量(

我认为应该将其定义为实例变量。

您能否指导我是否应在第一组中添加关键字static。

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.

一个相关的问题是:

是否应该将使用整个实例集合执行计算的方法也声明为静态/类方法?

当我尝试得到类似错误时rs尝试调用实例方法时。

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.

谢谢。

PS:关于本论坛:

我已经用代码块封闭了代码,但是Java语法未突出显示。

也许在我提交帖子后它会改变。
但是,如果有人可以告诉我,我很乐意重新格式化它。

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:这是一项家庭作业。

我已经在自己下面创建了所有代码。

作业标签已过时,因此我没有使用它。

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.

输入文件名: results.dat

输入文件路径: C:/ Users / ADMIN / Desktop / A1P3E1 Files / results.dat

输入文件内容(随机生成的数据):

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文件名: Exam.java

Java包名: a1p3e1

Java项目名: A1P3E1 < br>
Java文件内容:


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


推荐答案

readFile 是一个实例方法。创建 Exam 的实例以使用:

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

new Exam().readFile();

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

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.)

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

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.

在旁边:为了灵活起见,请使用 List 而不是固定大小的数组

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

Exam exam [];

可能是

List<Exam> examList; 

这篇关于(另一个)“不能从静态上下文引用非静态方法”。问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆