本文最后更新于:1 年前
🔺需求 👇
编写一个程序,其功能是能随机生成一个数组、同时完成对该数组的转置并打印输出转置后的数组。
🔺代码 👇
import static java.lang.System.out;
import java.util.Random;
public class Reverse2dArray {
static int[][] a; // 存放两位随机整数的int二维数组a
/**
* 构造方法,初始化数组a,r和c分别是行数和列数row column
*/
public Reverse2dArray(int r, int c){
a = new int[r][c];
buildRandArray();
}
/**
* 构造随机数组
*/
public void buildRandArray(){
Random random = new Random();
for(int i = 0; i < a.length; i++)
for(int j = 0; j < a[i].length; j++)
a[i][j] = random.nextInt(100);
}
/**
* 转置本类成员的二维数组a,并返回一个新的二维数组
* @return
*/
public int[][] reverse2dArray(){
int [][] b = new int [a[0].length] [a.length] ;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
b[j][i] = a[i][j] ;
}
}
return b ;
}
/* 显示二维数组 */
public void showArray(int[][] c){
out.printf("=========%2d×%-2d=========%n", c.length, c[0].length);
for(int[] cr : c){
for(int cc : cr){
out.printf("%5d ", cc);
}
out.println();
}
out.println("=======================");
}
public static void main(String[] args) {
int row = 3, col = 4;
Reverse2dArray me = new Reverse2dArray(row, col);
me.showArray(a); // 显示原数组
int[][] r = me.reverse2dArray();
me.showArray(r); // 显示转置的数组
}
}
🔺截图 👇
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!