簡體   English   中英

比較對象數組並從對象轉換為其原始類型

[英]Comparing array of objects and converting from an object to it's primitive type

我試圖從另一個類中找到對象數組的最低值,並將該對象int存儲為int類型。

我不確定如何比較數組值並將最小值存儲到int中。

void findlow(Student [] a) {
/* This method will find the lowest score and store it in an   array names 
lowscores. */
    for (int i = 0; i < (a.length - 1); i++) {
        for (int j = 1; i < a.length; i++) {
            if (a[i].equals(a[j])) {
                 lowscores[i] = a[i];
            }
        }
    }
}

使用lowscores[i] = a[i].(whatever integer variable); 整數變量應該是Student類中的getter或public int變量。 在Java中,您不能為對象設置int變量,這就是為什么該行可能會給您一個錯誤。

至於尋找得分最低,獲得的第一個指數a數組然后就檢查它是否小於下一個指標,如果它被設置為lowScore變量。

您有一個void方法“ findlow”; 這是令人困惑的,因為如果將其稱為find____,它將找到一些東西。

將您的問題分解為方法:

第一種方法-查找要查找的對象的最小值第二種方法-將結果放在某處

所以您可能需要第一種方法

public Student lowest(Student[] students) {
    Student result = students[0];
    for (Student s : students) {
        if (s.getProperty() < result.getProperty()) {
            result = s;
        }
    }
    return result;
}

第二

public void saveStudentInfo(Student student) {
    // do something with the student you found
}

所以總共

public static void main(String[] args) {
    // ...
    Student s = lowest(students);
    saveStudentInfo(s);
}

您的問題有點不清楚和模棱兩可。

我試圖從另一個類中找到對象數組的最低值,並將該對象int存儲為int類型。

首先,您可以輕松地將數組(從另一個類)傳遞到新類。 創建另一個類的對象,並簡單地引用數組。

示例:我假設另一個類的名稱為“ Other”,並且該類中的數組名為“ arr”。

Other other = new Other();
Student[] student = other.arr;

由於您正在進行數值比較,因此我還將假設您的Student類具有一個返回數值的方法(例如int)。 我們將此方法稱為getValue()。 現在,這就是您的findlow()方法應為:

int findlow(Student[] a){
    int low = a[0].getValue();
    for(int i = 1; i < a.length; i++){
        if(a[i].getValue() < low){
            low = a[i].getValue();
          }
        }
}//End of method.

我希望這有幫助!

快活的編碼!!!

暫無
暫無

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

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