Java Reference
In-Depth Information
As with one-dimensional arrays, an initializer list can be used to instanti-
ate a two-dimensional array, where each element is itself an array initializer
list. This technique is used in the SodaSurvey program, which is shown in
Listing 8.14.
LISTING 8.14
//********************************************************************
// SodaSurvey.java Author: Lewis/Loftus
//
// Demonstrates the use of a two-dimensional array.
//********************************************************************
import java.text.DecimalFormat;
public class SodaSurvey
{
//-----------------------------------------------------------------
// Determines and prints the average of each row (soda) and each
// column (respondent) of the survey scores.
//-----------------------------------------------------------------
public static void main (String[] args)
{
int [][] scores = { {3, 4, 5, 2, 1, 4, 3, 2, 4, 4},
{2, 4, 3, 4, 3, 3, 2, 1, 2, 2},
{3, 5, 4, 5, 5, 3, 2, 5, 5, 5},
{1, 1, 1, 3, 1, 2, 1, 3, 2, 4} };
final int SODAS = scores.length;
final int PEOPLE = scores[0].length;
int [] sodaSum = new int [SODAS];
int [] personSum = new int [PEOPLE];
for ( int soda=0; soda < SODAS; soda++)
for ( int person=0; person < PEOPLE; person++)
{
sodaSum[soda] += scores[soda][person];
personSum[person] += scores[soda][person];
}
DecimalFormat fmt = new DecimalFormat ("0.#");
System.out.println ("Averages:\n");
Search WWH ::




Custom Search