无法在基本类型double上调用方法

时间:2014-07-25 23:41:43

标签: java

我曾经参加了一个简介java类,尝试创建一个使用数组计算成绩的简单代码。我遇到了这个错误:

File: C:\Users\Owner\CS-121\GradeDriver.java  [line: 18]
Error: Cannot invoke getPoint() on the primitive type double

类和驱动程序如下:

public class Grade{
    private double point;

    public Grade(double x){
        point = x; 
    }

    public double getPoint(){
        return point; 
    }
}


public class GradeDriver{

    public static void main(String[] args){
        double score;
        double text = 0;
        double eoc = 0;
        double prog = 0;
        double mid = 0;
        double fin = 0;
        double[] textWork = {1.0,4.0,5.0,3.0,3.0,4.0,3.0,1.0,3.0,0.0,
                             9.0,4.0,5.0,6.0,5.0,3.0,5.0,3.0,1.0,1.0,
                             7.0,3.0,8.0,7.0,6.0,1.0,3.0,3.0,3.0,1.0,
                             4.0,2.0,3.0,8.0,1.0};
        double[] eocWork = {10.0,34.0,44.0,36.0,40.0,50.0,30.0,38.0,
                            14.0,40.0,12.0,26.0};
        double[] progWork = {10.0,10.0,5.0,7.0,7.0,9.0,10.0};
        double[] midTerm = {83.0};
        double[] finTerm = {68.0};

        for(int j = 0; j < textWork.length; j++){
            text = text + textWork[j].getPoint(); 
        }
        text = (text/132.0)*7.0;

        for(int j = 0; j < eocWork.length; j++){
            eoc = eoc + eocWork[j].getPoint(); 
        }
        eoc = (eoc/384.0)*15.0;

        for(int j = 0; j < progWork.length; j++){
            prog = prog + progWork[j].getPoint(); 
        }
        prog = (prog/70.0)*28.0;

        for(int j = 0; j < midTerm.length; j++){
            mid = mid + midTerm[j].getPoint(); 
        }
        mid = mid*0.15;

        for(int j = 0; j < finTerm.length; j++){
            fin = fin + finTerm[j].getPoint(); 
        }
        fin = fin*0.35;

        score = fin + mid + prog + eoc + text;
        System.out.println(score);
    }
}

1 个答案:

答案 0 :(得分:1)

更改这些循环:

for(int j = 0; j < textWork.length; j++) {
    text = text + textWork[j].getPoint();
}

为:

for(int j = 0; j < textWork.length; j++) {
    text = text + textWork[j];
}

你的数组包含双打,所以通过调用array[i]来调用索引i的值

此外,可以在包含它们的类的实例上调用方法。在这种情况下,您可以在类Grade的实例中调用getPoint()方法。例如:

Grade grade = new Grade(5.5);
grade.getPoint();

而是在数组的每个值上调用它,而不是类型Grade但是类型为double。因此问题

所有那些for循环基本上都是一样的,所以如果你有一个方法而不是那么多的重复代码会更好

e.g。

double sum(double[] array) {
    double result = 0;
    for(int i = 0; i < array.length; i++) {
        result += array[i];
    }
}

然后为所有数组调用方法并存储在变量

text = (sum(textWork)/132.0)*7.0;

等等。