A program shows how to work with two-dimensional arrays.
// read a 2-D array from the user (the rows may have different
// number of elements)
// Find the average of each row and the total average.
import java.io.*;
public class TwoD {
public static void main(String[] args) throws IOException {
// set up the reading
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
// string for storing a line of input
String line;
// read the number of rows
System.out.print("Please enter the number of rows: ");
line = in.readLine();
int rows = Integer.parseInt(line);
// initialize the array:
double [][] a = new double[rows][];
for(int i = 0; i < rows; ++i) {
// read the number of elements in this row:
System.out.print("How many elements are in row " + i + " ? ");
line = in.readLine();
int elts = Integer.parseInt(line);
// create an array for the row:
a[i] = new double[elts];
// read the elements
for (int j = 0; j < elts; ++j) {
System.out.print("Please enter the element " + j +
" of row " + i + " : ");
line = in.readLine();
a[i][j] = Double.parseDouble(line);
}
}
// computing the averages:
double sum = 0;
int total_elts = 0;
for (int i = 0; i < a.length; ++i) {
double sum_row = 0;
for (int j = 0; j < a[i].length; ++j) {
sum += a[i][j];
sum_row += a[i][j];
}
System.out.println("The average for row " + i + " is " +
sum_row/a[i].length);
total_elts += a[i].length;
}
System.out.println("The total average is " + sum/total_elts);
}
}
This is an example from CSci 1211 course.