2011-02-23 146 views
1

正量我想知道怎麼樣,如果可能的話,創建相同大小的數組的施氮量。幫助將不勝感激。例如:我想用相同數量的元素創建10個數組,而無需逐個創建它們:int[] a = new int[]。希望現在更清楚。創建陣列

我的一個在評論的一個問題是+ - 「我怎麼排序的行/列矩陣行列」。我明白了 - 也許有人會覺得它有用。

int[] sortarr = new int[5]; //create array to transfer data from row to new array 

for (int i=0; i<N; i++){ 
    for (int j=0; j<5; j++){ 
    sortarr[j] = hands[i][j]; //transfer the data from 2D array's row to sortarr 
    } 
    Arrays.sort(sortarr); //sort the row's data 

    for (int x=0; x<5; x++){ 
    hands[i][x] = sortarr[x]; //transfer the data back to 2D array 
    } 

} 

也許這很明顯,但我希望這會幫助那裏的人。

+0

你能澄清你的問題嗎?我不明白你想要做什麼。 – templatetypedef 2011-02-23 21:28:37

+0

你能提供更多信息嗎?你需要可變數量的數組嗎? – 2011-02-23 21:29:08

回答

5

您需要創建一個二維數組。

int n; 
int size; 
int[][] arr = new int[size][n]; 

可以填充具有嵌套for迴路陣列;

for(int i =0;i < arr.length; i++) { 
    for(int j = 0; i < arr[i].length; j++) { 
     arr[i][j] = someValue; 
    } 
} 

或者你可以填充像這樣的數組:

int[][] arr2 = new int[n][]; 
for(int i = 0; i < n; i++){ 
    arr2[i] = new int[size]; 
} 

你可以把一個二維數組作爲數組的數組,例如:

private Card[][] allPlayerHands; 
public Card[] getHand(int playerNumber) { 
    return allPlayerHands[playerNumber]; 
} 

這裏是一個很好關於二維數組堆棧溢出問題:

Initialising a multidimensional array in Java

+0

我不確定2D數組是否可以工作。我想洗牌一張牌,現在將這張牌交給5個不同的人。這五張牌需要分別保存在自己的陣列中。 – ISJ 2011-02-23 21:34:20

+0

@ISJ,你可以將二維數組看作一個數組的數組。看我的編輯。 – jjnguy 2011-02-23 21:35:15

+0

@ISJ在帖子中間做了另一個編輯,在2D數組中創建了許多1D數組。 – jjnguy 2011-02-23 21:44:15

0

INT [] I = {1,2,3,4,5}

INT [] J = i.clone()

你會得到大小與內容

3

二維數組是答案。讓我試着解釋

你需要處理的甲板上5個不同的人即詮釋人[5]。

現在考慮,每5人有5張牌,即

Guy 1: 1,2,3,4,5 
Guy 2: 1,2,3,4,5 
Guy 3: 1,2,3,4,5 
Guy 4: 1,2,3,4,5 
Guy 5: 1,2,3,4,5 

people[1]: 1,2,3,4,5 
people[2]: 1,2,3,4,5 
people[3]: 1,2,3,4,5 
people[4]: 1,2,3,4,5 
people[5]: 1,2,3,4,5 

people[5][5] 

現在,如果你要訪問的人1卡3那麼這將是

people[0][2] // u know its zero based aray 
+0

非常感謝,我說得很對;) – ISJ 2011-02-23 21:47:17