使用mySQL数据库在JSP中实现移动平均功能

时间:2019-02-18 06:46:34

标签: java mysql jsp netbeans xampp

我有一个移动平均样本代码,我想使用mySQL的数据来实现。

下面数组中的数据应该来自数据库而不是数组

double[] testData = {1, 2, 3, 4, 5, 5, 4, 3, 2, 1};

我该如何实施?

public class MovingAverage {

    private final Queue<Double> window = new LinkedList<Double>();

    private final int period;

    private double sum;

    public MovingAverage(int period) {

        assert period > 0 : "Period must be a positive integer";

        this.period = period;
    }

    public void newNum(double num) {

        sum += num;

        window.add(num);

        if (window.size() > period) {

            sum -= window.remove();
        }
    }

    public double getAvg() {

        if (window.isEmpty()) return 0.0; // technically the average is undefined

        return sum / window.size();

    }

    public static void main(String[] args) {

        double[] testData = {1, 2, 3, 4, 5, 5, 4, 3, 2, 1};

        int[] windowSizes = {3, 5};

        for (int windSize : windowSizes) {

            MovingAverage ma = new MovingAverage(windSize);

            for (double x : testData) {

                ma.newNum(x);

                System.out.println("Next number = " + x + ", SMA = " + ma.getAvg());

            }

            System.out.println();

        }
    }
}

0 个答案:

没有答案