【发布时间】:2015-02-04 04:28:06
【问题描述】:
该数组是名为 CO2Data 的类的一部分,因此该数组是一个 CO2Data 数组。问题是我试图找到数组中的最大值,但我的方法不起作用。要从数组中获取值,该方法必须首先从 CO2data 类中获取它们。那么我的方法有什么问题:
public static CO2Data highest (CO2Data [] arr2){
Scanner sc = null;
CO2Data highestindex = arr2[0].getTotalCO2;
for (int i = 0; i<arr2.length; i++){
arr2[i].getTotalCO2(sc.nextDouble());
if(arr2[i].getTotalCO2() > highestindex ) {
highestindex = arr2[i].getTotalCO2();
}
}
System.out.println(highestindex);
return highestindex;
}
CO2data 类如下所示:
公开课 CO2Data {
private String country; //A private variable will prevent other users from accessng and chaning these variables.
private double totalCO2;
private double roadCO2;
private double CO2PerPerson;
private int carsPerPerson;
public CO2Data() {
country = "";//this sets the initial values for the different variables
totalCO2 = 0;
roadCO2 = 0;
CO2PerPerson = 0;
carsPerPerson = 0;
}
public String getCountry() {
return country;
}
public void setCountry(String country) { //to set the country you have to use the this command to access the private variable
this.country = country; //you have to use this.country instead of just country because the string county has been declared as a private variable.
}
public double getTotalCO2() {
return totalCO2;
}
public void setTotalCO2(double totalCO2) {
this.totalCO2 = totalCO2; //The this.item command allows you to access private variables.
}
public double getRoadCO2() {
return roadCO2;
}
public void setRoadCO2(double roadCO2) {
this.roadCO2 = roadCO2;
}
public double getCO2PerPerson() {
return CO2PerPerson;
}
public void setCO2PerPerson(double cO2PerPerson) {
this.CO2PerPerson = cO2PerPerson;
}
public int getCarsPerPerson() {
return carsPerPerson;
}
public void setCarsPerPerson(int carsPerPerson) {
this.carsPerPerson = carsPerPerson;
}
}
【问题讨论】:
-
你不能在 Java 中使用原始比较运算符
<, ==, >, etc..比较Object类型 -
怎么了?您尝试从
Scanner读取,即null... -
@Kon
==当然适用于非原始类型 -
这不会编译.. (
highestindex = arr2[0];) -
@August - 是的。但是
==在您了解内存空间之前不会以您期望的方式工作。在您正在创建的类上覆盖equals方法是可行的方法。