gpt4 book ai didi

java - 如何编写一个方法来确定数组中的最大值

转载 作者:行者123 更新时间:2023-11-30 11:11:39 26 4
gpt4 key购买 nike

该数组是名为 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 类的样子:

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

最佳答案

我能看到的三个问题。

首先,您永远不会实例化 sc(您将其设置为 null,然后不对其进行任何操作)。

其次,您正在为对象设置 double 值。 (问题更新后不再有效)

第三,您正在将一个对象与一个 double 对象进行比较。

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

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

--编辑--此外,将 highestindex 行更改为:

CO2Data highestindex = arr2[0];

关于java - 如何编写一个方法来确定数组中的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27325427/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com