[英]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.