如何在Java中访问数组对象的特定元素?

时间:2016-01-23 23:24:29

标签: java arrays object element

此计划正在进行中。在其中,我为每个对象创建了一个包含五个不同数据类型的十个对象的数组。我需要找到q1的最高分,我希望通过创建一个循环,将变量highScore与每个q1数据(8,3,10,8,9,7.5,8.5,6,7.5,7)进行比较,以达到q1的最高分。循环经历了它的循环,然而,我收到一条错误消息,说明"运算符<未定义参数类型double,ClassGrade"在距离底部第二的线上。我不明白为什么我收到此错误消息,但我怀疑我得到它的原因是我没有正确指定我试图从每个对象访问的特定元素。任何有关此事的帮助将不胜感激。

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];

   }




}

}

4 个答案:

答案 0 :(得分:1)

首先,您需要在构造函数中分配实例变量。

您正在将双倍(高分)与ClassGrade(student [i])进行比较。

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

从数组访问对象的属性与从单个对象获取的方式相同。您从数组中获取对象并使用&#39;。&#39;访问其公共属性或方法。 E.g:

array[i].method()

答案 1 :(得分:0)

您正在将高分与数组中的实际对象进行比较,您正在将学生与成绩进行比较,因此只需进行一些小改动 - 在您的ClassGrade类中声明一个方法,如getQ1(),然后从中访问q1循环

答案 2 :(得分:0)

这应该有效:

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

答案 3 :(得分: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添加一个getter,然后使用它。

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

有关如何访问数组中对象成员的示例,请参阅here

相关问题