簡體   English   中英

我想將數組傳遞給另一個類,然后訪問數組中的特定項目以計算平均值,最大值或最小值

[英]I want to pass an array to another class, then access specific items in the array to calculate average, maximum or minimum

此類用於將現象的名稱存儲到數組。 如何將數組傳遞給Collat​​or類以獲取現象的平均值?

public class MonitoringStation {
    // Instance variables
    private String name;
    private Collator[] phenomena;
    private String phenomenonName;
    private double reading;
    private double average_value;
    private double sum;

    Collator collatorObject = new Collator(name);

    // Constructors
    public MonitoringStation(String name, String[] phenomenaNames) {
        // Create a MonitoringStation with the given name that will record statistics for the given phenomena.
        this.name = name;
        phenomena = new Collator[phenomenaNames.length];
        // System.out.println(phenomena.length);
    }

    // Methods
    public void recordReading(String phenomenonName, double reading) {
        // Update the records for the given phenomenon
        collatorObject.recordReading(reading);
        this.reading = reading;
        this.phenomenonName = phenomenonName;
    }

    public double average(String phenomenonName) {
        // Get the current value.
        return average_value;
    }
}

此類是負責測量現象的主要程序。

import java.util.Scanner;
//
public class StationUI {

    private StationUI() {}

    public static void main(final String[] args) {
        System.out.println("Monitoring Station Test Harness");
        final Scanner scanner = new Scanner(System.in);

        System.out.println("Enter the station name:");
        final String stationName = scanner.nextLine().trim();

        System.out.println("Enter a comma separated list of the phenomena to be recorded:");
        final String[] phenomena = scanner.nextLine().split("\\s*,\\s*");

        final MonitoringStation station = new MonitoringStation(stationName, phenomena);

        System.out.println("\nMake a selection and press return:");
        System.out.println("0.  Quit");
        System.out.println("1.  Record a phenomenon measurement.");
        System.out.println("2.  View the average reading for a phenomeon.");

        int selection = scanner.nextInt();

        while (selection!=0) {
            if (selection==1) {
                System.out.println("Enter the phenomenon name and value (e.g. 'temperature 7'):");
                if (scanner.hasNext()) {
                    final String phenomenon = scanner.next();
                    if (scanner.hasNextDouble()) {
                        final double reading = scanner.nextDouble();
                        station.recordReading(phenomenon, reading);
                    }
                    else {
                        System.out.println("Couldn't process phenomenon reading. Something wrong?");
                    }
                }
                else {
                    System.out.println("Couldn't process phenomeon name. Something wrong?");
                }                
            }
            else if (selection==2) {
                System.out.println("Enter the phenomenon name:");
                if (scanner.hasNext()) {
                    final String phenomenon = scanner.next();
                    System.out.printf("The average value for phenomeon %s is %.2f.\n", phenomenon , station.average(phenomenon));
                }
                else {
                    System.out.println("Couldn't process phenomeon name. Something wrong?");
                }
            }
            else {
                System.out.println("That selection was not recognised.");
            }

            System.out.println("\nMake a selection and press return:");
            System.out.println("0.  Quit");
            System.out.println("1.  Record a phenomenon measurement.");
            System.out.println("2.  View the average reading for a phenomeon.");

            selection = scanner.nextInt();
        }
        scanner.close();
    }
}

Collat​​or類處理這些值並獲取平均值,記錄的最小值和最大值以及現象的讀數次數。

/**
 * A Collator object stores statistics on a series 
 * of readings, specifically, the number, maximum, minimum, and average.
 * A Collator has a label, usually the name of the phenomenon that the readings
 * represent e.g. temperature, pressure.
 */
public class Collator {

    private final String label;
    private int numReadings;
    private double average;
    private double maximum;
    private double minimum;

    public Collator(final String label) {
        this.numReadings = 0;
        this.label = label;
    }

    public String label() { return label; } 

    public void recordReading(final double reading) {
        if (numReadings<1) {
            // This must be the first reading
            this.average = reading;
            this.maximum = reading;
            this.minimum = reading;
            this.numReadings = 1;
        }
        else {
            // Calculate the current total
            double total;
            total = this.average*this.numReadings;

            // Calculate the new total and update the number of readings
            total = total+reading;
            this.numReadings++;

            // Calculate the new average
            this.average = total/this.numReadings;

            // Check for a new maximum
            if (reading>this.maximum) {
                this.maximum = reading;
            }

            // Check for a new minimum
            if (reading<this.minimum) {
                this.minimum = reading;
            }
        } 
    }

    public double maximum() {
        assert this.numReadings>0 : "Collator:maximum(): number of readings is zero.";
        return this.maximum;
    }

    public double minimum() {
        assert this.numReadings>0 : "Collator:minimum(): number of readings is zero.";
        return this.minimum;
    }

    public double average() {
        assert this.numReadings>0 : "Collator:average(): number of readings is zero.";
        return this.average;
    }

    public int numberOfReadings() { return this.numReadings; } 
}

樣本I / O:

監控站測試線束
輸入電台名稱:
斑馬
輸入要記錄的現象的逗號分隔列表:
高度寬度
進行選擇,然后按回車鍵:
0.退出
1.記錄現象測量。
2.查看現象的平均讀數。
1個
輸入現象名稱和值(例如“溫度7”):
高度13.6
進行選擇,然后按回車鍵:
0.退出
1.記錄現象測量。
2.查看現象的平均讀數。
1個
輸入現象名稱和值(例如“溫度7”):
高度12
進行選擇,然后按回車鍵:
0.退出
1.記錄現象測量。
2.查看現象的平均讀數。
1個
輸入現象名稱和值(例如“溫度7”):
寬100
進行選擇,然后按回車鍵:
0.退出
1.記錄現象測量。
2.查看現象的平均讀數。
2
輸入現象名稱:
高度
現象高度的平均值是12.80。
進行選擇,然后按回車鍵:
0.退出
1.記錄現象測量。
2.查看現象的平均讀數。
0

只需創建一個接收數組並計算內容的公共方法,如下所示:

public double calculateAverage(double[] arraysName){

    //calculate it using the arraysName

    return average;
}

因此,在創建具有此方法的對象時,可以在此處調用它。
我不確定這是否是您想要的答案,如果您已經執行了發布的代碼,這對我來說似乎很基礎,我可能有錯誤的想法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM