
Patrick B. answered 05/04/20
Math and computer tutor/teacher
You're on the right track, but in the for loop, you have to compare the variable col against the size of data[i].length, or else you are going to compare it against something NULL or undefined, and then it crashes!!!
Here ya go:
class AngieARaggedArrays
{
public static final int MAX_COLUMNS=6;
/*********************************************
Returns the largest column value or -1
************************************************/
public static double getHighestInColumn(double[][]data, int col)
{
double maxVal=-1;
for (int rowLoop=0; rowLoop<data.length; rowLoop++)
{
if (
(col>=0) && (col<data[rowLoop].length)
)
// Then that column EXISTS in this particular row
{
if ( data[rowLoop][col]>maxVal) //the current max value has been DEFEATED!!
{ // new champion ;-)
maxVal = data[rowLoop][col];
}
}
}
return(maxVal);
}
public static void main(String args[])
{
double A[][] = { {5, 4, 3, 2, 1},
{4, 3, 2},
{1, 4, 7, 9, 3, 5},
{7, 8, 4, 1, 2},
{9, 3},
{1, 3, 3, 4, 5},
{2},
{7, 6, 5, 4}
};
AngieARaggedArrays x = new AngieARaggedArrays();
for (int columnLoop=0; columnLoop<x.MAX_COLUMNS; columnLoop++)
{
System.out.println(" The highest value in column " + columnLoop
+ " is : " +x.getHighestInColumn(A,columnLoop));
}
}
}