2016-01-23 78 views
0

这个程序是一个正在进行的工作。其中,我为每个对象创建了包含五种不同数据类型的十个对象的数组。我需要找到q1的最高分数,我希望通过创建一个循环来将变量highScore与每个q1数据(8,3,10,8,9,5.5,8.5,6,7.5,7)进行比较该循环经历了它的循环,但是,我收到一条错误消息,指出“运算符<未定义为参数类型double,ClassGrade”,位于底部第二行。我不明白为什么我得到这个错误消息,但我怀疑我得到它的原因是,我没有正确指定我想要从每个对象访问的特定元素。任何关于此事的帮助将不胜感激。如何在Java中访问数组对象的特定元素?

public class ClassGrade { 
public String studentID; 
public double q1; 
public double q2; 
public int mid; 
public int finalExam; 


public ClassGrade(String studentID, double q1, double q2, int mid, int finalExam) 
{ 
    // TODO Auto-generated constructor stub with a few modifications 
} 

public static void main(String[] args) { 
    System.out.println("this program works"); 
    double highScore; 
    highScore = 0; 
    ClassGrade [] student = new ClassGrade[10]; 
    student[0] = new ClassGrade ("A1", 8, 8.5, 84, 82); 
    student[1] = new ClassGrade ("B2", 3, 7, 0, 99); 
    student[2] = new ClassGrade ("C3", 10, 9.5, 92, 84); 
    student[3] = new ClassGrade ("D4", 8, 8, 89, 86); 
    student[4] = new ClassGrade ("E5", 9, 10, 83, 91); 
    student[5] = new ClassGrade ("F6", 7.5, 8.5, 88, 69); 
    student[6] = new ClassGrade ("G7", 8.5, 0, 81, 52); 
    student[7] = new ClassGrade ("H8", 6, 8.5, 79, 68); 
    student[8] = new ClassGrade ("I9", 7.5, 6, 72, 91); 
    student[9] = new ClassGrade ("J10", 7, 6.5, 58, 77); 
    for(int i=0; i<10; i++){ 
     if (highScore < student[i]) 
      highScore = student[i]; 

    } 




} 

}

+3

提示1:

int score = student[i].getQ1() if (highScore < score) highScore = score; 

为如何在一个数组访问对象的成员的示例见here的TODO是有一个很好的理由:) – qqilihq

+0

另一个提示:学生[I]的访问该索引处的ClassGrade对象。您仍然需要指定诸如student [i] .q1之类的字段。 –

回答

1

首先,你需要指定你的实例变量在你的构造函数。

你正在比较一个双(高分)与ClassGrade(学生[我])。

您需要在ClassGrade中创建公共方法来返回所需的属性。

从数组访问对象的属性与从单个对象访问对象的方式相同。您从数组中获取对象并使用'。'访问其公共财产或方法。例如:

array[i].method()

0

您的高分与数组中的实际对象比较,你是比较级的学生,所以只是做一些小的变化 - 在你ClassGrade类中声明的方法一样getQ1(),然后从循环进入Q1

0

这应该工作:

ClassGrade classGrade = (ClassGrade) student[i]; 
classGrade.method(); 
+0

你能解释它是如何帮助吗? – Phani

0

阵列的每个成员仍然是一个ClassGrade,因此,所有你需要做的是检查其q1我像你一样的任何其他ClassGrade的q1。

for(int i=0; i<10; i++){ 
    if (highScore < student[i].q1) 
     highScore = student[i].q1; 
} 

想一想,就好像数组索引是名称的一部分,它会更有意义。

// Consider this: 
studentZero = new ClassGrade("A1", 8, 8.5, 84, 82); 

if (highScore < studentZero) 
    highScore = studentZero; 

// studentZero is not a double. Therefore... 
if (highScore < studentZero.q1) 
    highScore = studentZero.q1; 

或者,您可以为q1添加吸气剂并使用它。