矩阵行和列

时间:2015-12-28 18:49:31

标签: java matrix

我无法在列和行中运行此矩阵只有一列?

如何添加5列和5行

我认为问题出在最后一段代码上。

static Scanner in = new Scanner(System.in);
public static void main(String[] args) {

    int l,c, aux;
    int matrix[][]={
                        {99,21,4,8,19},
                        {4,8,44,1,12},
                        {36,73,29,87,3},
                        {21,55,4,12,10},
                        {16,66,3,42,8}};

    int nl=matrix.length;
    int nc=matrix[0].length;
    int []vect=new int[nc];
    for(int i=0;i<nl;i++){  
         vect=matrix[i];
         if(i%2==0){
             vect = SelectionSortCustom(vect, vect.length,true);
         }
         else{
             vect = SelectionSortCustom(vect, vect.length,false);
         }           
         matrix[i] = vect;
    }

    System.out.println("Matricea sortata este:");
    PrintMatrix(matrix);
}

public static int[] SelectionSortCustom(int[] array, int n, boolean flag)
{
    int aux, min, max, minat, maxat;
    for(int i=0;i<n;i++){
        if(flag==true)  //true=> par => crescator
        {
            minat=i;
            min=array[i];
            for(int j=i+1; j<n; j++){
                if(flag==true){
                    if(min>array[j])
                        {
                            minat = j;
                            min=array[j];                          
                        }
                }
            }
            aux = array[i];
            array[i] = array[minat];
            array[minat] = aux;
        }
        if(flag==false) //true=> impar => descrescator
        {
            maxat = i;
            max = array[i];
            for(int j=i+1; j<n; j++){
                    if(max<array[j])
                        {
                            maxat = j;
                            max=array[j];                          
                        }
                }
            aux = array[i];
            array[i] = array[maxat];
            array[maxat] = aux;
        }
    }
    return array;
}

public static int[][] ReadMatrix(int row, int col){
    int[][] matrix = new int[row][col];
    for(int i=0;i<row;i++)
        for(int j=0;j<col;j++){
            matrix[i][j] = in.nextInt();
        }
    return matrix;
}

public static void PrintMatrix(int[][] matrix){
    int row = matrix.length;
    int col = matrix[0].length;
    for(int i=0;i < row;i++)            {
        for(int j=0;j < col;j++){
            System.out.println(matrix[i][j] + " ");
        }          
        System.out.println();
    }
  }
}

1 个答案:

答案 0 :(得分:1)

您在每个值后打印新行。

更改此

System.out.println(matrix[i][j] + " ");

到此

System.out.print(matrix[i][j] + " ");