小心! 2020-12-12 15:57 采纳率: 57.1%
浏览 346
已采纳

java练习,定义二维数组,将其转置并按矩阵方式输出结果。

  1. 定义二维数组,将其转置并按矩阵方式输出结果。
  • 写回答

2条回答 默认 最新

  • 晨曦之光Wing 2020-12-12 18:08
    关注
    public class ArrayTranspose {
    
        public static void main(String[] args) {
            // 三行四列的数组
            int[][] array = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
            System.out.println("原数组:");
            printArray(array);
    
            // 四行三列的数组
            int[][] newArray = transpose(array, array.length, array[0].length);
            System.out.println("转置后:");
            printArray(newArray);
        }
    
        private static int[][] transpose(int[][] array, int originRowLength, int originColLength) {
            // 原来的数组的行数等于新数组的列数
            // 原来的数组的列数等于新数组的行数
            int[][] newArray = new int[originColLength][originRowLength];
            // 以原数组的行数和列数为基础
            for (int rowIndex = 0; rowIndex < originRowLength; rowIndex++) {
                for (int colIndex = 0; colIndex < originColLength; colIndex++) {
                    // 行列转换:原来的行索引是新的列索引,原来的列索引是新的行索引
                    newArray[colIndex][rowIndex] = array[rowIndex][colIndex];
                }
            }
            return newArray;
        }
    
        private static void printArray(int[][] newArray) {
            for (int rowIndex = 0; rowIndex < newArray.length; rowIndex++) {
                for (int colIndex = 0; colIndex < newArray[0].length; colIndex++) {
                    System.out.print(newArray[rowIndex][colIndex] + "\t");
                }
                System.out.println();
            }
        }
    
    }
    

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码