编程完成二维数组的转置并输出转置前后的数组元素。要求转置和输出都用方法完成
时间: 2024-05-03 19:23:18 浏览: 14
Java代码如下:
```java
public class TransposeArray {
public static void main(String[] args) {
int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
System.out.println("转置前:");
printArray(arr);
int[][] transArr = transpose(arr);
System.out.println("转置后:");
printArray(transArr);
}
// 转置数组
public static int[][] transpose(int[][] arr) {
int row = arr.length;
int col = arr[0].length;
int[][] transArr = new int[col][row];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
transArr[j][i] = arr[i][j];
}
}
return transArr;
}
// 输出数组元素
public static void printArray(int[][] arr) {
for (int[] row : arr) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
}
}
```
输出结果:
```
转置前:
1 2 3
4 5 6
7 8 9
转置后:
1 4 7
2 5 8
3 6 9
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)