public static void main (String args[])
{ int f = Integer.parseInt(JOptionPane.showInputDialog("Cuantas filas"));
int c = Integer.parseInt(JOptionPane.showInputDialog("Cuantascolumnas"));
int [][]mat = new int[f][c];int cont = 0;
while(cont < 2)
{ int [][]columR = redef_colum(mat);
mat = columR;
/* int [][]filaR = redef_fila(mat);
mat = filaR;*/
cont++;
}
String result = "";
for(int x = 0; x < mat.length; x++)
{ for(int y = 0; y< mat[x].length; y++)
{ result += mat[x][y] + " "; } result += "\n";};
JOptionPane.showMessageDialog(null,result); }
public static int[][] redef_colum(int m[][])
{
int[][] redef_colum = new int [m.length][m.length + 1];
for(int f = 0; f < redef_colum.length; f++)
{ for(int c = 0; c < redef_colum[f].length; c++)
{ if(c < redef_colum.length)
{ redef_colum[f][c] = m[f][c];}
else
{redef_colum[f][c] = 0;}
}
}
return redef_colum;
}
public static int[][] redef_fila(int m[][])
{
int[][] redef_fila = new int [m.length +1][m.length];
for(int f = 0; f < redef_fila.length; f++)
{
if(f < redef_fila[f].length)
{ for(int c = 0; c < redef_fila[f].length; c++)
{ redef_fila[f][c] = m[f][c];}
}
else{
for(int c = 0; c < redef_fila[f].length; c++)
{ redef_fila[f][c] = 0; }
}
}
return redef_fila;
}
-
tambien publica el Main o funcion principal, y especifica un poco mas tu problema es muy amplio. – Shassain el 13 ago. 17 a las 20:46
1 respuesta
1 - Revisando el código que colocas encuentro que el primer error esta en la linea
int[][] redef_colum = new int[m.length][m.length + 1];
Esto a que estas definiendo la matriz redef_colum
con solo el número de filas; esta línea debería ser
int[][] redef_colum = new int[m.length][m[0].length + 1];
2 - Esta parte del ciclo de copiado no es necesaria
if (c < redef_colum.length) {
redef_colum[f][c] = m[f][c];
} else {
redef_colum[f][c] = 0;
}
debido a que a)
cuando defines una matriz de enteros está por default se llena con el valor cero 0
y b)
Siempre vas a copiar a una matriz mayor por lo cual solo debes recorrer la matriz original (matriz m
) y pasarla a la matriz destino (matriz redef_colum
).
for (int f = 0; f < m.length; f++) {
for (int c = 0; c < m[f].length; c++) {
redef_colum[f][c] = m[f][c];
}
}
Ahora, esto es valido si y solo si, la matriz origen tiene datos, por que si esta vacia (toda la matriz en cero) no es requerido hacer este copiado.
3 - Debes hacer los mismos cambios en el método public static int[][] redef_fila(int m[][])
4 - Para recorrer la matriz y almacenar sus valores en una sola variable String, es preferible que uses un StringBuilder
.
StringBuilder result = new StringBuilder();
for (int x = 0; x < mat.length; x++) {
for (int y = 0; y < mat[x].length; y++) {
result.append(mat[x][y]);
result.append(" ");
}
result.append("\n") ;
}
JOptionPane.showMessageDialog(null, result.toString());