This might sound stupid but I can't get it to work. After reading how many rows and how many columns a matrix has, I'm trying to display the minimum element on each row, then the minimum element on each column.
My code looks like this, but sometimes it throws an IndexOutOfBoundsException, sometimes it just doesnt display the minimum for the columns, only for the rows.
The code for the rows, which works, is this
public static void minRand(int[][] n) {
int[] result = new int[n.length];
int min = 0;
for (int i = 0; i < n.length; i++) {
for (int j = 0; j < n[0].length; j++) {
if (n[i][j] < n[i][min]) {
min = j;
}
result[i] = n[i][min];
}
System.out.println("Minimum on line " + i + " is " + result[i]);
}
}
And the code for the columns, which does not work is
public static void minCol(int[][] n) {
int[] result = new int[n[0].length];
int min = 0;
for (int i = 0; i < n.length; ++i) {
min = Integer.MAX_VALUE;
for (int j = 1; j < n[i].length; ++j)
if (n[j][i] < min)
min = n[j][i];
System.out.println("Minimum on column no " + i + " is " + min);
}
}
If i give it 3 lines and 4 columns, the console displays this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Principal.minCol(Principal.java:103)
at Principal.afisareMeniu(Principal.java:196)
at Principal.main(Principal.java:13)
Minimum on line 0 este 0
Minimum on line 1 este 0
Minimum on line 2 este 0
It's 0 because i didnt initialize the matrix, but the minimum on each line works.
Also. If i give it a square matrix, both the minimum for rows and columns work. What am i doing wrong?