Multi-Dimensional Arrays
public class TwoWayTable {
int numRows;
int numCols;
int[][] cell;
int[] rowSum;
int[] colSum;
int grandTotal;
// constructor
TwoWayTable(int[][] data)
{
//Here I want to initialize and assign values
//not sure how?
setMargins();
}
void setMargins()
{
//Here I want to compute the row and column sums;
}
public String toString()
{
// Here I want to format the table using the toString()
}
}
Not sure how to implement the above multi-dimensional array. Any help on this is greatly appreciate it...Thanks in advance.
///
The following is my test program
public class TestTwoWayTable {
public static void main(String[] args) {
int i, j;
int[][] testArray = {
{2, 5, 6, 3}, {9, 4, 4, 7},
{1, 10, 2, 3}, {8, 4, 5, 3} };
TwoWayTable t = new TwoWayTable(testArray);
System.out.println(t);
}
}
normaly it should produce output something like the following:
2 5 6 3 | 16
9 4 4 7 | 24
1 10 2 3 | 16
8 4 5 3 | 20
--
20 23 17 16 | 76
[1187 byte] By [
exl5a] at [2007-11-27 7:27:31]

Hi
You can use the following *rough* code:
class TwoWayTable {
int[][] cell;
int[] rowSum;
int[] colSum;
int grandTotal = 0;
// constructor
TwoWayTable(int[][] data)
{
cell = data;
setMargins();
}
void setMargins()
{
try {
// Init rowSum and colSum
rowSum = new int[cell.length];
colSum = new int[cell.length];
// Calculate row Sum
for (int row = 0; row < cell.length; row++) {
for (int col = 0; col < cell[row].length; col++) {
rowSum[row] += cell[row][col];
}
}
// Calculate col Sum
for (int col = 0; col < cell[0].length; col++) {
for (int row = 0; row < cell.length; row++) {
colSum[col] += cell[row][col];
}
grandTotal += colSum[col];
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String toString()
{
StringBuffer results = new StringBuffer();
for (int row = 0; row < cell.length; row++) {
for (int col = 0; col < cell[row].length; col++) {
results.append(cell[row][col] + " ");
}
results.append("| " + rowSum[row] + "\n");
}
results.append("--\n");
for (int col = 0; col < cell[0].length; col++) {
results.append(colSum[col] + " ");
}
results.append("| " + grandTotal + "\n");
return results.toString();
}
}
public class TestTwoWayTable {
public static void main(String[] args) {
int[][] testArray = {
{2, 5, 6, 3}, {9, 4, 4, 7},
{1, 10, 2, 3}, {8, 4, 5, 3} };
TwoWayTable t = new TwoWayTable(testArray);
System.out.println(t);
}
}
> Thanks for the suggestions..!! Youre absolutely
> correct.It does make it a little neater..so can you
> replace all the 'For Loops' with an enhanced
> one..without the compiler yelling at you?
The new for loop is not meant to do everything the old one can.