2017-01-20 71 views
-6

我有一個多維數組:Java的多維數組拆分

// nums[3][0] 
String[][] nums = new String[3][0]; 
nums = {{32,123,74},{543,98,5},{96,24,23},{12,98,56}} 
System.out.println(nums[0][0])

臨屋輸出32, 123, 74 我要拆分的列,所以輸出應該是這樣的:

System.out.println(nums[0][0]); // Output: 32 
System.out.println(nums[1][2]); // Output: 5 

我試過nums[0][0] = nums[0][0].split(",");但出現錯誤

我被卡住了,我無法做到。

+3

歡迎來到StackOverflow!如果你告訴我們你已經嘗試了什麼,即使它不起作用,人們也會更傾向於幫助你。然後,我們可以幫助您指引正確的方向。如果我們只是爲了解決你的問題,你就不會真正學到任何東西。 – Michael

+2

代碼不能編譯。你不能在字符串數組中使用整數。您的結果數組與起始數組相同。 –

+0

你能告訴我在{{32,123,74},{543,98,5},{96,24,23},{12,98,56}}和'{{32,123,74}}之間有什麼不同嗎? {543,98,5},{96,24,23},{12,98,56}}'? –

回答

3

我希望我已經正確理解你想問什麼。

首先,因爲它已經提到你不能在String數組中存儲整數。其次,在Java中二維數組實際上是數組的數組。因此,當您聲明int[][] nums = int[4][3]時,您將創建一個int[]數組nums,該數組有四個元素,每個元素都是另一個int[]數組。長度爲3.因此,如果您想象您的二維數組是矩陣類型,則可以輕鬆地檢索它的「行」作爲nums數組的元素。

int[][] nums = {{32, 123, 74}, {543, 98, 5}, {96, 24, 23}, {12, 98, 56}}; 

int[] rowOne = nums[0];  // {32, 123, 74} 
int[] rowTwo = nums[1];  // {543, 98, 5} 
int[] rowThree = nums[2]; // {96, 24, 23} 
int[] rowFour = nums[3]; // {12, 98, 56} 

只要它們不存在java的話,獲得「列」就有點棘手。但你仍然可以這樣做,如下所示:

int[] columnOne = new int[nums.length]; 
for (int i = 0; i < columnOne.length; i++) { 
    columnOne[i] = nums[i][0]; // {32, 543, 96, 12} 
} 

int[] columnTwo = new int[nums.length]; 
for (int i = 0; i < columnTwo.length; i++) { 
    columnTwo[i] = nums[i][1]; // {123, 98, 24, 98} 
} 

int[] columnThree = new int[nums.length]; 
for (int i = 0; i < columnThree.length; i++) { 
    columnThree[i] = nums[i][2]; // {74, 5, 23, 56} 
}