简体   繁体   中英

How to exclude numbers from array sum/average/min/max?

I'm working on an assignment for class and I'm trying to figure out how to get the average of the numbers in my array while excluding the number -999 (used to indicate missing data) I've figured out how to get the sum/average/min/max and whatnot but I cannot figure out how to exclude that -999 from the search range. You can see in the first few methods a few of the things I've tried so far to figure this out. I can't even find anything on google that might even begin to explain what I'm supposed to be doing right now. 在此处输入图片说明 These are the instructions I'm following and the below is my current code, thanks for any input you may have.

    /**
 * WeatherComputation.java
 */

//Put any imports below this line.
import java.util.*;

/**
 * Static methods library which compute averages and other
 * computations on integer arrays of temperatures.
 * 
 * @author Joel Swanson 
 * @version 03.29.2014
 */
public class WeatherComputation
{    
    /**
     * Average an array of temperatures.
     * @param temperatures An array storing temperatures as ints.
     * @return Returns the average of the array of ints.
     */
    public static double averageTemperature(int[] temperatures)
    {   
        int sum = 0;
        for (int i = 0; i < temperatures.length; i++)
        {
         sum += temperatures[i];
        }
        double average = sum / temperatures.length;
        return average;
    }

    /**
     * Find the highest in an array of temperatures.
     * @param temperatures An array storing temperatures as ints.
     * @return The largest value from the the array of ints.
     */
    public static int highestTemperature(int[] temperatures)
    {      
        int max = temperatures[0]; 
        for (int i = 1; i < temperatures.length; i++)
        {
            if(temperatures[i] > max)
            { 
                max = temperatures[i]; 
            } 
        }
        return max;
    } 

    /**
     * Find the lowest in an array of temperatures.
     * @param temperatures An array storing temperatures as ints.
     * @return The lowest value from the the array of ints.
     */
    public static int lowestTemperature(int[] temperatures)
    {
        int min = 0; 
        Arrays.sort(temperatures);

        while (true)
        {
            if (min == -999)
            {
                break;   
            }

            if(min > -999)
            {
                min = temperatures[0];
            }
        }

        for (int i = 1; i < temperatures.length; i++)
        {
            if (min < -999)
            {
                if (temperatures[i] < min)
                {
                    min = temperatures[i];   
                }    
            }
        } 

        return min;
    }

    /**
     * Return the total number of missing days.  That is days with
     * -999 recorded as the temperatures.
     * @param temperatures An array storing temperatures as ints.
     * @return The number of -999s found.
     */
    public static int numberMissing(int[] temperatures)
    {       
        int count = 0; 

        return count;
    } 

    /**
     * Calculate heating degree day.
     * @param max The highest temperature for a given day.
     * @param min The lowest temperature for a given day.
     * @return heating degree day data for this day.
     */
    public static double hdd(int max, int min)
    {
        double hdd = 0.0;

        return hdd;
    }

    /**
     * Calculate cooling degree day.
     * @param max The highest temperature for a given day.
     * @param min The lowest temperature for a given day.
     * @return cooling degree day data for this day.
     */
    public static double cdd(int max, int min)
    {
        double cdd = 0.0;

        return cdd;
    }    

    /**
     * Sum monthly heating degree days.
     * @param max An array with the highest temperatures for each day
     * in a given month.
     * @param min An array with the lowest temperatures for each day
     * in a given month.
     * @return The sum of the heating degree days.
     */
    public static double monthHdd(int[] max, int[] min)
    {
        double sum = 0.0;

        return sum;        
    }

    /**
     * Sum monthly cooling degree days.
     * @param max An array with the highest temperatures for each day
     * in a given month.
     * @param min An array with the lowest temperatures for each day
     * in a given month.
     * @return The sum of the cooling degree days.
     */
    public static double monthCdd(int[] max, int[] min)
    {
        double sum = 0.0;

        return sum;        
    }     
}

You really want to use Java 8's stream operators for this. If I take your code, and leave out the methods that aren't implemented, and that don't describe what is actually being calculated, I get this:

/**
 * WeatherComputation.java
 */
import java.util.*;
import java.util.stream.IntStream;

/**
 * Static methods library which compute averages and other
 * computations on integer arrays of temperatures.
 *
 * @author Joel Swanson
 * @version 03.29.2014
 */
public class WeatherComputation {

    /**
     * Filters out all missing values (represented by -999).
     *
     * @param temperaturs an array storing temperatures as ints.
     * @return the list with the missing values removed
     */
    private static IntStream getFilteredArray(final int[] temperaturs) {
        return IntStream.of(temperaturs)
                .filter(i -> i != -999);
    }

    /**
     * Average an array of temperatures.
     *
     * @param temperatures an array storing temperatures as ints.
     * @return the average of the array of ints.
     */
    public static double averageTemperature(int[] temperatures) {
        // Returns 0 on an empty list. Your code will throw an exception
        return getFilteredArray(temperatures).average().orElse(0d);
    }

    /**
     * Find the highest in an array of temperatures.
     *
     * @param temperatures an array storing temperatures as ints.
     * @return the largest value from the the array of ints.
     */
    public static int highestTemperature(int[] temperatures) {
        return getFilteredArray(temperatures).max().orElse(0);
    }

    /**
     * Find the lowest in an array of temperatures.
     *
     * @param temperatures an array storing temperatures as ints.
     * @return the lowest value from the the array of ints.
     */
    public static int lowestTemperature(int[] temperatures) {
        return getFilteredArray(temperatures).min().orElse(0);
    }

    /**
     * Return the total number of missing days. That is days with
     * -999 recorded as the temperatures.
     *
     * @param temperatures an array storing temperatures as ints.
     * @return the number of -999s found.
     */
    public static int numberMissing(int[] temperatures) {
        return (int) IntStream.of(temperatures)
                .filter(t -> t == -999)
                .count();
    }
}

The method getFilteredArray does all the work. It converts the array into an IntStream , it removes all -999 values, and returns the stream. Then you can use stream operators to calculate things like average, sum, minimum, maximum, etc.

public static double averageTemperature(int[] temperatures)
    {   
        int sum = 0;
        int count = 0;// number of valid values
        for (int i = 0; i < temperatures.length; i++)
        {
            if(temperatures[i] > -999){ // before calculating check value
                  count ++;
                  sum += temperatures[i];
             }
        }
        double average = count != 0 ? sum / count : -999 - 1; // preventing divide by zero
        return average;
    }

public static int lowestTemperature(int[] temperatures) {
    if(temperatures == null || temperatures.length == 0)
        return -999 - 1;
    int min = temperatures[0];
    for (int temperature : temperatures) {
        if (temperature > -999 && temperature < min) {
            min = temperature;
        }
    }
    return min;
}

You just need to check at each step if the value is the excluded one before using it in your sum/average/min/max methods.

For instance:

public static double averageTemperature(int[] temperatures) 
{   
    int sum = 0;
    int count = 0;
    for (int i = 0; i < temperatures.length; i++) 
    {
       if (temperatures[i] != -999) {
           sum += temperatures[i];
           count++;
       }
    }
    double average = sum / count;
    return average;
}

For the lowestTemperature, this is what I would do:

public static int lowestTemperature(int[] temperatures) {
    int min = 999;
    for (int temperature : temperatures) {
        if (temperature > -999 && temperature < min) {
            min = temperature;
        }
    }
    return min;
}

Assuming that your WeatherComputation class would also consider 999 the same way as it would consider -999 (an invalid value). The reason is simple, what if you only have negative values during a month? Then, your int min = 0 would be incorrect.

As for the averageTemperature:

public static double averageTemperature(int[] temperatures) {
    int sum = 0, validTemperatureCounter = 0;
    for (int temperature : temperatures) {
        if (temperature > -999 && temperature < 999) {
            validTemperatureCounter++;
            sum += temperature;
        }
    }
    return sum / (double)validTemperatureCounter;
}

I also took the liberty of ignoring the value 999 .

Update

For fun, one liners:

public static double averageTemperatureOneLiner(int[] temperatures) {
    return Arrays.stream(temperatures).filter(t -> t > -999 && t < 999).average().orElse(0);
}


public static int lowestTemperatureOneLiner(int[] temperatures) {
    return Arrays.stream(temperatures).filter(t -> t > -999 && t < 999).min().orElse(0);
}


public static int highestTemperatureOneLiner(int[] temperatures) {
    return Arrays.stream(temperatures).filter(t -> t > -999 && t < 999).max().orElse(0);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM