Algs4-1.1.13编写一段代码,打印出一个M行N列的二维数组的转置(交换行和列)

本文提供了一段Java代码,用于实现M行N列二维数组的转置操作,即交换行和列。代码首先初始化了一个指定大小的字符串二维数组,并填充了数组元素,然后分别打印了原始数组和转置后的数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.1.13编写一段代码,打印出一个M行N列的二维数组的转置(交换行和列)。
public  class Test
{
    public static void main(String[] args)
    {
     //初始化
     int M=Integer.parseInt(args[0]);
     int N=Integer.parseInt(args[1]);
     String[][] array=new String[M][N];
     for (int row=0;row<M;row++)
         for(int col=0;col<N;col++)
              array[row][col]=row+","+col;
     //打印未转置的元素
     int width=Integer.toString(M).length()+ Integer.toString(N).length()+1+4;
     String format="%"+Integer.toString(width)+"s";
     StdOut.printf(format," ");
      for (int col=0;col<N;col++)
          StdOut.printf(format,col);
      StdOut.printf("\n");
      //
      for (int row=0;row<M;row++)
      {
          StdOut.printf(format,row);
           for (int col=0;col<N;col++)
                 StdOut.printf(format,array[row][col]);
          StdOut.printf("\n");
      }
    //打印转置后的元素
      StdOut.printf("\n\n\n");
      StdOut.printf(format," ");
      for (int row=0;row<M;row++)
          StdOut.printf(format,row);
      StdOut.printf("\n");
      //
      for (int col=0;col<N;col++)
      {
          StdOut.printf(format,col);
           for (int row=0;row<M;row++)
                 StdOut.printf(format,array[row][col]);
          StdOut.printf("\n");
      }
       }//end main
}//end class
图片

转载于:https://www.cnblogs.com/longjin2018/p/9848507.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值