簡體   English   中英

如何在Java中訪問數組對象的特定元素?

[英]How do I access a specific element of an object of an array in Java?

該程序正在進行中。 在其中,我創建了一個包含十個對象的數組,每個對象具有五種不同的數據類型。 我需要找到q1的最高得分,我希望通過創建一個循環來比較變量highScore與每個q1數據(8、3、10、8、9、7.5、8.5、6、7.5、7),以實現最高得分循環經歷了整個循環,但是,我從底部倒數第二行收到一條錯誤消息,指出“對於參數類型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];

   }




}

}

首先,您需要在構造函數中分配實例變量。

您正在將Double(高分)與ClassGrade(student [i])進行比較。

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

從數組訪問對象的屬性與從單個對象訪問對象的屬性相同。 您從數組中獲取對象並使用'。'。 訪問其公共屬性或方法。 例如:

array[i].method()

您正在將高分與數組中的實際對象進行比較,將學生與年級進行比較,因此只需做一些小改動-在ClassGrade類中聲明一個方法,如getQ1() ,然后從循環中訪問q1

這應該工作:

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

數組的每個成員仍然是ClassGrade ,因此您需要像檢查其他ClassGrade的q1一樣檢查其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添加一個吸氣劑並使用它。

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

有關如何訪問數組中對象的成員的示例,請參見此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM