Замена строк матрицы - Java

Мне нужно написать код для загрузки квадратной матрицы, затем поменять местами первую строку со строкой с наибольшим элементом в первом столбце, а затем распечатать обмененный массив.

Я могу получить самый большой элемент первого столбца, но я не знаю, как сделать обмен.

import java.io.*;
import java.util.*;
import static java.lang.System.out;

class Matriz4_Metodos{

    static String cadena;
    static InputStreamReader entrada = new InputStreamReader(System.in);
    static BufferedReader recibedatos = new BufferedReader(entrada);

    public static void main (String[] args) throws java.io.IOException {
    int n,mayor=0;

    n=LeerNumero("Ingresa el numero de los renglones y columnas:");

    int Matriz[][] = new int [n][n];

    Matriz=CargarMatriz(Matriz);

    ImprimirMatriz(Matriz);

    out.println("\nEl mayor de la primera columna es:"+EncontrarMayor(Matriz,mayor));

    }

    public static int LeerNumero (String msgtxt) throws java.io.IOException{

        do{
        int xnm;
        out.print(msgtxt);
        cadena=recibedatos.readLine();
        try{
        xnm=Integer.parseInt(cadena);
            if (xnm<0){
             out.println("Solo positivos");
             continue;
            }
            return xnm;
        }   
            catch (NumberFormatException e){
                out.println("Numero de dato incorrecto");
            }
        }while(true);

    }

    public static int[][] CargarMatriz (int xMatriz[][]) throws java.io.IOException{
    Random Aleatorio =new Random();
    int nal;
        for(int i=0; i<xMatriz.length; i++){
            for(int j=0; j<xMatriz[0].length; j++){
                nal=Aleatorio.nextInt(10);
                xMatriz[i][j]=nal;
            }

        }

        return xMatriz;
    }

    public static void ImprimirMatriz (int xMatriz[][]){
        out.println("\n");
        for(int i=0; i<xMatriz.length; i++){
            for(int j=0; j<xMatriz[0].length; j++){
                out.print(xMatriz[i][j]+" ");
            }
            out.println("\n");
        }
    }

    public static int EncontrarMayor (int xMatriz[][],int xmayor) throws java.io.IOException {
        xmayor=0;

        for(int i=0; i<xMatriz.length; i++){
            for(int j=0; j<xMatriz[0].length; j++){
                if(j==0){
                    if(xMatriz[i][j]>xmayor){
                    xmayor=xMatriz[i][j];
                    }
                }
            }
        }
        return xmayor;
    }

}

person user3522262    schedule 13.04.2014    source источник
comment
Пожалуйста, покажите, что вы сделали, чтобы решить эту проблему. Где ты застрял?   -  person Braj    schedule 13.04.2014
comment
извините забыл код   -  person user3522262    schedule 13.04.2014
comment
Если вы собираетесь задать новый вопрос, вам следует закрыть свой предыдущий повторяющийся вопрос\.   -  person Hovercraft Full Of Eels    schedule 13.04.2014


Ответы (2)


Найдите ответ на свой предыдущий вопрос Матричная замена столбцов — Java поменять местами столбцы.

Вот код. Для получения дополнительной информации прочитайте встроенные комментарии.

    int[][] arr = new int[][] { { 1, 4, 5, 4 }, { 7, 6, 4, 2 }, { 1, 1, 2, 3 }, { 1, 2, 2, 5 } };

    for (int i = 0; i < arr.length; i++) {
        for (int j = 0; j < arr[i].length; j++) {
            System.out.print(arr[i][j] + "\t");
        }
        System.out.println();
    }

    // logic begins here
    int rowWithHighestValueInFirstColumn = 1;
    for (int i = 0; i < arr[rowWithHighestValueInFirstColumn].length; i++) {
        // store the value of highest row
        int temp = arr[rowWithHighestValueInFirstColumn][i];
        // swap the value of highest row with first row
        arr[rowWithHighestValueInFirstColumn][i] = arr[0][i];
        // set the value of first row that is stored in temp
        arr[0][i] = temp;
    }
    // logic ends here

    System.out.println("After swapping");
    for (int i = 0; i < arr.length; i++) {
        for (int j = 0; j < arr[i].length; j++) {
            System.out.print(arr[i][j] + "\t");
        }
        System.out.println();
    }

вывод: (вторая строка заменяется первой)

    1   4   5   4   
    7   6   4   2   
    1   1   2   3   
    1   2   2   5   
    After swapping
    7   6   4   2   
    1   4   5   4   
    1   1   2   3   
    1   2   2   5
person Braj    schedule 13.04.2014

Поскольку матрица представляет собой массив массивов, вы можете просто поменять местами строки, как только найдете индекс строки с наибольшим числом. Измените свой метод EncontrarMayor так, чтобы он возвращал индекс строки, а не самый большой элемент, а остальное будет простым. Вот соответствующие изменения в вашем коде. (Помимо изменения логики метода EncontrarMayor, я переименовал его, чтобы он соответствовал стандартным соглашениям об именах Java, и удалил бесполезный второй аргумент):

public static void main(String[] args) {
    ...
    int renglonMayor = encontrarMayor(matriz);
    out.println("\nEl mayor de la primera columna es:" + matriz[renglonMayor][0]);
    int[] renglon = matriz[0];
    matriz[0] = matriz[renglonMayor];
    matriz[renglonMayor] = renglon;
    ... // print the matrix
}

public static int encontrarMayor (int xMatriz[][]) throws java.io.IOException {
    int renglonMayor = 0;
    int numeroMayor = xMatrix[0][0];

    for(int i=1; i<xMatriz.length; i++){
        if(xMatriz[i][0]>numeroMayor){
            numeroMayor = xMatrix[i][0];
            renglonMayor = i;
        }
    }
    return renglonMayor;
}
person Ted Hopp    schedule 13.04.2014