import java.text.DecimalFormat; // for formatting /** * A class to illustrate the use of a 2D array.
* The methods of the class initialize a 2D array, namely an array to store the * daily rainfall amount over 3 months. The monthly rainfall average is * computed. */ public class TwoDimensionalArray { public static void main(String[] args) { new TwoDimensionalArray().processRainfall(); } /** * Initialize a 2D array to store the daily rainfall over a 3 months period * (namely April, May and June). Do initialization in a private method * (assign to each element a random double between 0 and 10).
* Then, compute and print the monthly rainfall average. */ public void processRainfall() { // Store in an array the daily rainfall // over a period of 3 months (April, May, June) // rainfall should be an array of 3 1D arrays (each 1D array // is of size 30, 31 and 30). double[][] rainfall = new double[3][]; rainfall[0] = new double[30]; // April rainfall[1] = new double[31]; // May rainfall[2] = new double[30]; // June // Initialize the array // (call fillRandomly) fillRandomly(rainfall); /* // side point: don't use a for each loop to // initialize an array // example with a 1D array double[] b = new double[20]; for(double val: b) { val = Math.random(); } // not the same as for (int i = 0; i < b.length; i ++) { b[i] = Math.random(); } */ // Compute and print the average rainfall for each month // (call computeAndPrintMonthlyAverage) computeAndPrintMonthlyAverage(rainfall); } /** * Initialize the elements of a 2D array with a random double between 0 and * 10. * * @param rainfall * the array to initialize */ private void fillRandomly(double[][] rainfall) { // Fill randomly the array with a random value between 0 and 10 for (int i = 0; i < rainfall.length; i ++) { for (int j = 0; j < rainfall[i].length; j ++) { rainfall[i][j] = 10 * Math.random(); } } } /** * Compute and print the average daily rainfall for each month * * @param rainfall * the array to average */ private void computeAndPrintMonthlyAverage(double[][] rainfall) { DecimalFormat df = new DecimalFormat("0.00"); // String[] month = new String[3]; // month[0] = "April"; // month[1] = "May"; // month[2] = "June"; // Better here to write String[] month = {"April", "May", "June"}; int index = 0; for (double[] row: rainfall) { double sum = 0; for (double value: row) { sum += value; } System.out.println( "The daily average rainfall for the month of " + month[index] + " is " + df.format(sum/row.length)); index ++; } } }