本文實例講述了java實現二維數組轉置的方法。分享給大家供大家參考,具體如下:
這里在文件中創建Test2、Exchange、Out三個類
在Exchange類中編寫exchange()方法,在方法中創建兩個數組arraryA、arraryB,arraryB[j][i]=arraryA[i][j]實現數組的轉置。
在Out類中編寫out()方法,在方法中用for循環遍歷實現輸出。
具體代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
package Tsets; import java.util.*; public class Test2 { public static void main(String args[]) { Out T1= new Out(); Out T2= new Out(); Exchange E= new Exchange(); System.out.println( "服務器之家測試結果:" ); System.out.println( "轉置前的二維數組如下:" ); T1.out(E.arraryA); E.exchange(); System.out.println( "轉置后的二維數組如下:" ); T2.out(E.arraryB); } } //數組轉置 class Exchange { int arraryA[][]={{ 11 , 12 , 13 , 14 , 15 },{ 21 , 22 , 23 , 24 , 25 },{ 31 , 32 , 33 , 34 , 35 },{ 41 , 42 , 43 , 44 , 45 },{ 51 , 52 , 53 , 54 , 55 }}; int arraryB[][] = new int [arraryA[ 0 ].length][arraryA.length]; public void exchange () { for ( int i= 0 ;i<arraryA.length;i++) { for ( int j= 0 ;j<arraryA[i].length;j++) { arraryB[j][i]=arraryA[i][j]; } } } } //數字循環遍歷輸出 class Out { public void out( int c[][]) { for ( int i= 0 ;i<c.length ;i++ ) { for ( int j= 0 ;j<c[i].length ;j++ ) { System.out.print(c[i][j]+ " " ); } System.out.println(); } } } |
運行結果:
希望本文所述對大家java程序設計有所幫助。