1 public class ArrayChange {
2 /**
3 * 数组行和列变换的方法
4 *
5 * @param array
6 * 需要chang的数组
7 * @return chang以后的数组
8 */
9 public int[][] change(int[][] array) {
10 for (int i = 0; i < array.length; i++) {
11 for (int j = 0; j < i; j++) {
12 int a = array[i][j];
13 array[i][j] = array[j][i];
14 array[j][i] = a;
15 }
16 }
17 return array;
18 }
19
20 public static void main(String[] args) {
21 int[][] array = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 },
22 { 13, 14, 15, 16 } };
23 System.out.println("数组变化之前:");
24 for (int i = 0; i < array.length; i++) {
25 for (int j = 0; j < array.length; j++) {
26 System.out.print(array[i][j]);
27 if (array[i][j] < 10) {
28 System.out.print(" ");
29 } else {
30 System.out.print(" ");
31 }
32 }
33 System.out.println();
34 }
35 ArrayChange arrayChange = new ArrayChange();
36 int[][] a = arrayChange.change(array);
37 System.out.println("数组变化之后:");
38 for (int i = 0; i < a.length; i++) {
39 for (int j = 0; j < a.length; j++) {
40 System.out.print(a[i][j]);
41 if (a[i][j] < 10) {
42 System.out.print(" ");
43 } else {
44 System.out.print(" ");
45 }
46 }
47 System.out.println();
48 }
49 }
50
51 }
输出结果:
思路:对数组进行遍历,然后通过第三个元素交换元素。注意:矩阵必须是n*n,否则会报数组越界(原因自己想想就知道了^.^)
愿你悄悄的努力,遇见更好的自己~