如何编写方法来确定数组中的最高值

时间:2014-12-05 22:05:27

标签: java arrays class

该数组是名为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;
}

这是CO2数据类的样子:

公共类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;
    }
}

2 个答案:

答案 0 :(得分:1)

我可以看到三个问题。

首先,你永远不会实例化sc(你把它设置为null,然后不用它)。

其次,您要为对象设置双倍。 (问题更新后不再有效)

第三,您正在将对象与双精度进行比较。

您很可能想要比较对象的属性。也许是这样的:

if( arr2[i].getTotalCO2() > highestindex.getTotalCO2() ) {
    highestindex = arr2[i];
}

- EDIT-- 另外,将highestindex行更改为:

CO2Data highestindex = arr2[0];

答案 1 :(得分:0)

我确定你的代码不是代码。

例如,你如何做到这一点:

double highestindex = arr2[0];

或者您的方法中的Scanner类有什么意义?它不起作用。

如果你把这么奇怪的代码放在这里很难帮到你。 试试这个:

public static double highest (CO2Data []  arr2){
    Scanner sc = new Scanner(System.in);
    CO2Data highestindex = arr2[0];
    for (int i = 0; i<arr2.length; i++){
    arr2[i].setTotalCO2(sc.nextDouble());
        if (arr2[i].getTotalCO2() > highestindex.getTotalCO2()){
            highestindex = arr2[i];
            }
        }
    System.out.println(highestindex.getTotalCO2());
    return highestindex.getTotalCO2();
    }