【问题标题】:How to sort a matrix in a row-wise manner in java如何在java中以行方式对矩阵进行排序
【发布时间】:2023-02-23 01:44:45
【问题描述】:

我一直在尝试按行方式对矩阵的元素进行排序。但是,当我尝试对它们进行分类时,我得到了错误 error: incompatible types: int cannot be converted to int[][]。由于某种原因,我找不到消除错误的方法。

下面是我制作的代码。

import java.util.Scanner;
import java.util.Arrays;
public class arrayinput2{
    
    static void sortByRow(int m[][], int n){
        for (int i = 0; i < n; i++)
            Arrays.sort(m[i]);
    }
    
    static void transpose(int m[][], int n){
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
                {
                int temp=m[i][j];
                m[i][j]=m[j][i];
                m[j][i]=temp;
                }
    }
    
    static void sortMatRowAndColWise(int m[][],int n)
    {
        sortByRow(m, n);
        transpose(m, n);
        sortByRow(m, n);
        transpose(m, n);
    }
    
    static void printMat(int m[][], int n)
    {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++)
                System.out.print(m[i][j] + " ");
            System.out.println();
        }
    }
    
    public  static void main(String args[]){
        int m,n,i,j;
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter the number of rows: ");
        m = sc.nextInt();
        n = m;
        
        int array[][] = new int[m][n];
        System.out.println("Enter the elements of the array: ");
        for(i=0;i<m;i++)
            for(j=0;j<n;j++)
        array[i][j] = sc.nextInt();
        

        System.out.println("Elements of the array are: ");
        printMat(m, n);
    }
}

【问题讨论】:

  • 无关:请坚持 Java 命名约定
  • 旁注:您根本没有在发布的代码中调用sortMatRowAndColWise()

标签: java matrix user-input


【解决方案1】:

您使用了不一致的命名约定。

在某些方法中,m 作为参数指的是二维数组。

但是,在您的main() 中,您已将m 声明为int

改变:

printMat(m, n);

到:

printMat(array, n);

【讨论】:

    【解决方案2】:

    为什么会这样

    1- m 是您的 main 方法中的整数类型,并保留行数。

    2- printMat(int m[][],int n) 方法接受一个二维数组和一个整数。

    3-当您运行 printMat(m,n) 时,您尝试将一个整数放入二维数组。(考虑 printMat(int m[][],int n) 中的 'm' 和 int m; 中的 'm' 是不一样。)

    你该怎么办

    你应该写 printMat(array,n) 而不是 print(m,n)。

    【讨论】:

      猜你喜欢
      • 2018-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-03
      • 1970-01-01
      相关资源
      最近更新 更多