2013-08-29 51 views
1
int[ ][ ] num=new int[5][ ]; 
num[0]=new int[1]; 
num[1]=new int[5]; 
num[2]=new int[]; 
num[3]=new int[3]; 

鋸齒陣列可以打印在一個循環中還是需要兩個循環?在一個循環中打印鋸齒陣列表

+3

2維= 2個嵌套循環。 –

+0

這不是一個數組列表,它是一個數組。 – arshajii

+1

@JunedAhsan我認爲OP意味着鋸齒。 –

回答

2

需要兩個循環;一個用於循環數組數組,另一個用於遍歷每個嵌套數組並打印相應的元素。你也可以簡單地使用Arrays.deepToString()(使用循環內部):

int[][] num = new int[5][]; 
num[0] = new int[1]; 
num[1] = new int[5]; 
num[2] = new int[0]; 
num[3] = new int[3]; 

System.out.println(Arrays.deepToString(num)); 
 
[[0], [0, 0, 0, 0, 0], [], [0, 0, 0], null] 
+0

由於'deepToString'在Integer []而不是int []上工作,所以這不起作用。自動裝箱對數組原語不起作用 – Jatin

+0

@arshajii這是一個java版本依賴參數 – Cruncher

+0

@Jatin *「如果元素'e'是一個基本類型的數組,它將被轉換爲一個字符串,如同調用' Arrays.toString(e)'。如果一個元素'e'是一個引用類型的數組,它將被遞歸地調用這個方法轉換爲一個字符串。「* – arshajii

0

你可以通過避免使用Arrays.toString()寫內環。

for(int[] row: num) { 
    System.out.println(Arrays.toString(row)); 
} 

但是你的代碼實際上並不快。它仍然使用引擎蓋下的for循環。

1
void printRaggedArray(int[][] ragged) { 
    int outer = 0; 
    int inner = 0; 
    while(outer < ragged.length) { 
     if(inner >= ragged[outer].length) { 
      inner=0; 
      outer++; 
      continue; 
     } 
     System.out.println[outer][inner++]; 
    } 
} 

這可行,但2迴路更好。這不會更快,實際上它可能會更慢。

+1

創意。我應該說它回答了這個問題!正如你所說,沒有人會想要使用它,雖然... –

+0

大聲笑,我不記得寫這個答案,但它絕對有點厚顏無恥。它基本上只是用計數器實現一個內部循環 – Cruncher

+0

@Ole V.V我把它清理了很多,因爲你喜歡它 – Cruncher

0
public class Main { 
    public static void main(String args[]) { 
    int twoD[][] = new int[4][]; 
    twoD[0] = new int[1]; 
    twoD[1] = new int[2]; 
    twoD[2] = new int[3]; 
    twoD[3] = new int[4]; 

    for (int i = 0; i < 4; i++){ 
     for (int j = 0; j < i + 1; j++) { 
     twoD[i][j] = i + j; 
     } 
    } 
    for (int i = 0; i < 4; i++) { 
     for (int j = 0; j < i + 1; j++) 
     System.out.print(twoD[i][j] + " "); 
     System.out.println(); 
    } 
    } 
}