Home > DeveloperSection > Forums > How do I write a method to determine the highest value in an array
Pravesh Singh
Pravesh Singh

Total Post:101

Posted on    December-29-2014 10:59 PM

 Java Java  Array  Class 

 1 Reply(s)
 522  View(s)
Rate this:
The array is part of a class called CO2Data so the array is a CO2Data array. The problem is I'm trying to find the highest value in the array but my method isn't working. To get the values from the array the method must first get them from the CO2data class. So what's wrong with my method:

    public static CO2Data highest (CO2Data []  arr2){
Scanner sc = null;
CO2Data highestindex = arr2[0].getTotalCO2;
for (int i = 0; i<arr2.length; i++){
if(arr2[i].getTotalCO2() > highestindex ) {
    highestindex = arr2[i].getTotalCO2();
return highestindex;
Here's what the CO2data class looks like:

public class 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;

Jayden Bell
Jayden Bell

Total Post:105

Posted on    December-30-2014 12:53 AM

Three problems that I can see.

First, you are never instantiating sc (you set it to null, then do nothing with it).

Second, you are setting a double to an Object. (no longer valid after question update)

Third, you are comparing an object with a double.

Most likely you want to compare properties of the object. Maybe something like:

if( arr2[i].getTotalCO2() > highestindex.getTotalCO2() ) {
    highestindex = arr2[i];
Also, change the highestindex line to:

CO2Data highestindex = arr2[0];

Don't want to miss updates? Please click the below button!

Follow MindStick