此题以用Java将一个5x3的二维数组转置输出为例。
源代码 :
package helloworld;
import java.util.*;
public class transpose {
public static void main (String age[]) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个5*3的矩阵:");
int[][] matrix = new int[5][3];
int[][]matrix1 = new int[3][5];
for(int i = 0; i<matrix.length; i++)
for(int j =0; j<matrix[0].length; j++)
{
matrix[i][j] = sc.nextInt();
}
System.out.println("输出转置后的矩阵:");
for(int i = 0; i<matrix.length; i++)
{ for(int j =0; j<matrix[0].length; j++)
{
matrix1[i][j] = matrix[j][i];
System.out.print(matrix1[i][j]+" ");
}
System.out.println();
}
}
}
结果:
改报错意思下标为3的数组索引超出范围,经检查可知
在此段的代码,i,和j 的取值范围有问题。此段进行循环的主体是matrix1数组,而不是matrix数组,所以这里的代码改为
for(int i = 0; i<matrix1.length; i++)
{ for(int j =0; j<matrix1[0].length; j++)
{
matrix1[i][j] = matrix[j][i];
System.out.print(matrix1[i][j]+" ");
}
System.out.println();
}
正确总代码:
package helloworld;
import java.util.*;
public class transpose {
public static void main (String age[]) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个5*3的矩阵:");
int[][] matrix = new int[5][3];
int[][]matrix1 = new int[3][5];
for(int i = 0; i<matrix.length; i++)
for(int j =0; j<matrix[0].length; j++)
{
matrix[i][j] = sc.nextInt();
}
System.out.println("输出转置后的矩阵:");
for(int i = 0; i<matrix1.length; i++)
{ for(int j =0; j<matrix1[0].length; j++)
{
matrix1[i][j] = matrix[j][i];
System.out.print(matrix1[i][j]+" ");
}
System.out.println();
}
}
}
若有不足之处请及时纠正。谢谢!(本小白一枚~)