仅检查数组的某些值以获得最大阈值

时间:2017-04-25 17:07:07

标签: java netbeans javafx

我有一个基本上监控具有9个通道的温度探头的程序。在这9个频道中,8个(有时是7个)频道非常重要,它们不会超过一定的温度。我最初写的方法如下:

    public boolean isAverageGreaterThanMax(double max) {
        //return DoubleStream.of(values).allMatch(v -> v <= max);
        double averageValue = DoubleStream.of(values).average().getAsDouble();
        if (averageValue > max)
        {
            System.out.println("The Average of values is: " + averageValue + " The Max is: " + max);
            System.out.println("max met!");
            return true;
        }
        else
        {
            return false;
        }

    }

然而,这假设所有频道都以相似的速度上涨,这是不正确的,因为我最近得到的情况是一个频道是WAY WAY up并且正在扭曲整个平均值。 我需要检查所有通道(或8或7)是否超过一定的阈值,所以我想到这样的事情:

    public boolean isAverageGreaterThanMax(double max, int ch) {
        for (int i=0; i<ch; i++)
        {
            // CHECK ONLY AS MANY CHANNELS AS CH VARIABLE THAT WAS INPUTTED
            // IF ALL OF THE CHECK CHANNELS ARE ABOVE MAX TEMPERATURE RETURN TRUE
            // IF NOT THEN KEEP WAITING UNTIL ALL OF THEM ARE
        }
    }

但是我似乎无法想出怎么做,因为我只想要它,如果所有这些,但是如果我使用if循环,那么每个人都可以返回一个真实的。
我希望我很清楚,并提前感谢你。

2 个答案:

答案 0 :(得分:0)

当然你只是轮流检查每一个。如果任何低于最大值,则返回false,如果它们都不低于最大值,则返回true。

public boolean isAverageGreaterThanMax(double max, int ch) {
    for (int i=0; i<ch; i++)
    {
        if (values[i] <= max) return false ;
    }
    return true ;
}

或使用流:

public boolean isAverageGreaterThanMax(double max, int ch) {
    return DoubleStream.of(values).limit(ch).allMatch(v -> v > max);
}

但也许我误解了这个问题。

答案 1 :(得分:0)

我不确定我是否正确理解了您的问题,但这可能会对您有所帮助。

    public static void main(String[] args) {

    double[] temperatures = new double[] { 50, 60, 70, 80, 90 };
    int minimalRequiredChannelCount = 3;

    if (DoubleStream.of(temperatures).allMatch(x -> yourRequirementCheck(x))) {
        System.out.println("all channels were fulfilling your requirement");
    } else {
        System.out.println("there was a channel not fulfilling the requirement");
    }

    long channelsFulFillingTheRequirementCount = DoubleStream.of(temperatures).filter(x -> yourRequirementCheck(x)).count();
    System.out.println(channelsFulFillingTheRequirementCount + " channels were fulfilling the requirement, min. required:" + minimalRequiredChannelCount);

    if (channelsFulFillingTheRequirementCount >= minimalRequiredChannelCount) {
        System.out.println("there were enough channels fulfilling the requirement");
    } else {
        System.out.println("there were NOT enough channels fulfilling the requirement");
    }

    double averageOfAllValidChannels = DoubleStream.of(temperatures).filter(x -> yourRequirementCheck(x)).average().orElse(-99999);
    System.out.println("the average temperature was:" + averageOfAllValidChannels);

}

public static boolean yourRequirementCheck(double temp) {
    if (temp > 55) {
        return true;
    } else {
        return false;
    }
}