I have a problem that involves matrices, what I need to do is fill a matrix of N * M of dimension (that is, of a number n of columns and rows given by the user), with even numbers, which already huh got. My inconvenience is generated when I am going to deploy this matrix, since when the number of rows is greater than that of the columns, I have an error which is this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at diagonal.pkg2.Diagonal2.main (Diagonal2.java:40) D: \ Users \ Jefferson \ AppData \ Local \ NetBeans \ Cache \ 8.2 \ executor-snippets \ run.xml: 53: Java returned: 1
But, otherwise, when the matrix is of form n * m and the rows do not exceed the one of the columns or it is square, there is no problem Attached runs of each case:
run when the number of rows is greater than the number of columns
Here is another problem too, since just after its main diagonal, all its values are zero (which should not be the case)
run of the program, when the number of rows is less than the number of columns and the error
How can I solve these problems? I leave the code:
int filas;
int columnas;
BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
System.out.println("Ingrese el nro de filas para la matriz: ");
filas=Integer.parseInt(br.readLine());
System.out.println("Ingrese el nro de columnas para la matriz: ");
columnas=Integer.parseInt(br.readLine());
//definimos las variables para almacenar la matriz y de control
int fila, columna, ultimaColumnaInicio, ultimaFilaInicio;
int matriz[][];
int valor = 2;
matriz = new int[filas][columnas];
ultimaColumnaInicio = columna = columnas - 1;
ultimaFilaInicio = fila = 0;
do {
matriz[fila++][columna++] = valor;
if (columna == columnas) {
fila = 0;
columna = --ultimaColumnaInicio;
} else if (fila == filas) {
fila = ++ultimaFilaInicio;
columna = 0;
}
valor = valor + 2;
} while ((fila != filas));
for(int i=0; i < filas; i++) {
for(int j=0; j < columnas; j++) {
System.out.print(String.format("%3d", matriz[i][j]) +" ");
}
System.out.println("");
}