显示转置方法的问题?

时间:2015-10-01 18:47:20

标签: java arrays matrix transpose

我试图编写一个打印随机生成的矩阵和转置矩阵的程序,但我无法弄明白。 当我尝试编译时,我在第41行和第34行得到错误;错误:找不到符号printMatrix(transposedMatrix);             ^ 我已经为此工作了几个小时,现在无法弄明白,提前感谢您的帮助。

如果此代码的格式有点偏差,我很抱歉,在Sublime看起来很好,而且我不习惯这个网站。

import java.util.Scanner;

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

int rows = 0;
int cols = 0;

while (rows < 1 || rows > 10) {
System.out.print("Enter the number of rows (1-10): ");
int userRows = input.nextInt();

if (userRows < 1 || userRows > 10) {
  System.out.println("ERROR! The number of rows cannot be outside the specified range of 1-10!");
}
else userRows += rows;
}

while (cols < 1 || cols > 10) {
System.out.print("Enter the number of columns (1-10): ");
int userCols = input.nextInt();

if (userCols < 1 || userCols > 10) {
  System.out.println("ERROR! The number of columns cannot be outside the speified range of 1-10!");
}
else userCols += cols;
}

int[][] originalMatrix = new int[rows][cols];

for (int row = 0; row < originalMatrix.length; row++)
  for (int col = 0; col < originalMatrix[row].length; col++) {
    originalMatrix[row][col] = (int) (Math.random() * 1000);
  }

System.out.println("\nOriginal matrix:");
printMatrix(originalMatrix);

System.out.println("\nTransposed matrix:");
printMatrix(transposedMatrix);
}

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

public static int[][] transposedMatrix(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int[][] transposedMatrix = new int[n][m];
for(int x = 0; x < n; x++) {
    for(int y = 0; y < m; y++) {
        transposedMatrix[x][y] = matrix[y][x];
    }
}
return transposedMatrix;
}
}

2 个答案:

答案 0 :(得分:2)

更改print语句以调用您创建的方法。确保也传递C:\

originalMatrix

同样偏离主题但您的代码中存在内存泄漏。使用后,您永远不会关闭printMatrix(transposedMatrix(originalMatrix));。最好在使用完毕后关闭扫描仪。将其添加到Scanner方法的末尾以停止内存泄漏。

main

答案 1 :(得分:0)

client

这应该是

System.out.println("\nTransposed matrix:");
printMatrix(transposedMatrix);