I'm trying to demonstrate various array operations, and have a couple of questions. I'm having problems with printing out the column and row totals. It only prints out the totals of the last row and last column. It also only prints out the lowest of row 1 and the highest of row 3. I need it to give the row totals of each row, etc. Help?
public class ArrayOperations
{
public static void main (String [] args)
{
int [] [] numbers = {{1,2,3,4},
{5,6,7,8},
{9,10,11,12}};
int total;
int row = 0;
int col = 0;
int totalOfArray = getTotal(numbers);
int averageOfArray = getAverage(numbers);
int rowTotalOfArray = getRowTotal(numbers);
int columnTotalOfArray = getColumnTotal(numbers);
int rowHighest = getHighestInRow(numbers);
int rowLowest = getLowestInRow(numbers);
System.out.println("The sum of all the numbers in the array is:" + totalOfArray + ".");
System.out.println("The average of the numbers in the array is:" + averageOfArray + ".");
System.out.println("The sum of row " + row + " is " + rowTotalOfArray + ".");
System.out.println("The sum of column " + col + " is " + columnTotalOfArray + ".");
System.out.println("The lowest number of row " + row + " is " + rowLowest + ".");
System.out.println("The highest number of row " + row + " is " + rowHighest + ".");
}
public static int getTotal (int [] [] numbers) //takes a two-dimensional array and returns the total of the values in the array.
{
int total = 0; //Accumulator set to 0
//Sum the array elements.
for (int row = 0; row < numbers.length; row++)
{
for (int col = 0; col < numbers [row].length; col++)
total +=numbers[row][col];
}
return total;
}
public static int getAverage(int [] [] numbers) //takes two dimensional array and returns the average of the values.
{
int total = 0; //Accumulator, set to 0
for (int row = 0; row < numbers.length; row++)
{
for (int col = 0; col<numbers [row].length; col++)
total +=numbers[row][col];
}
return total/numbers.length;
}
public static int getRowTotal (int [] [] numbers)
{
int total = 0;
for (int row = 0; row<numbers.length; row++)
{
//Set accumulator to 0.
total = 0;
//Sum a row.
for (int col = 0; col <numbers[row].length; col++)
total += numbers[row][col];
}
return total;
}
public static int getColumnTotal (int [] [] numbers)
{
int total = 0; //Accumulator
for (int col = 0; col<numbers[0].length; col++)
{
//Set the accumulator to 0.
total = 0;
//Sum a column.
for (int row = 0; row < numbers.length; row++)
total += numbers[row][col];
}
return total;
}
public static int getLowestInRow (int [] [] numbers)
{
int low = numbers [0] [0];
for (int row = 1; row < numbers.length; row++)
{
for (int col =1; col<numbers[row].length; col++)
{
if (numbers[row][col] < low)
low = numbers[row][col];
}
}
return low;
}
public static int getHighestInRow (int [] [] numbers)
{
int high = numbers [0] [0];
for (int row = 1; row < numbers.length; row ++)
{
for (int col =1; col<numbers[row].length; col++)
{
if (numbers[row][col] > high)
high = numbers[row][col];
}
}
return high;
}
}