2012-11-17 58 views
4

所以我試圖重複一個int []數組中的值。 所以基本上,如果你有一個數組 {1,2,3,4} 你的輸出就會重複數組

{1,2,2,3,3,3,4,4,4,4} 

或者如果你

{0,1,2,3} 

你的輸出

{1,2,2,3,3,3}. 

我確信,必須有在這裏是兩個for循環,但我似乎無法弄清楚代碼,使它複製數組中的值。 我不能得到2,2,2, 任何幫助將不勝感激,謝謝。

編輯在這裏,我想代碼會工作

public static int[] repeat(int []in){ 
    int[] newarray = new int[100]; 

    for(int i = 0; i<=in.length-1;i++){ 

     for(int k= in[i]-1;k<=in[i];k++){ 

      newarray[i] = in[i]; 

     } 
    } 
    return newarray; 
} 

我認爲這會工作,但它只是返回相同的列表,或有時如果我改變它周圍生病剛剛得到4新數組英寸

+6

請顯示您到目前爲止嘗試過的方法。請記住,stackoverflow不是一個代碼工廠... – home

+0

你必須弄清楚2件事:新數組的大小以及如何將舊值放入新數組中。第一個問題可以通過一個簡單的循環來解決,而第二個問題可以通過嵌套循環來解決,就像你提到的那樣。 – jma127

+0

無論如何你都在使用它?也許有一個更好的解決方案,您正試圖解決的問題。 – Sietse

回答

1

這將動態地構建正確的大小的新數組,然後填充它。

int[] base = { 1, 2, 3, 4 }; 
    int size = 0; 
    for(int count : base){ 
     size += count; 
    } 

    int[] product = new int[size]; 

    int index = 0; 
    for(int value : base){ 
     for(int i = 0; i < value; i++){ 
      product[index] = value; 
      index++; 
     } 
    } 

    for(int value : product){ 
     System.out.println(mine); 
    } 
+0

這個解決方案效果很好,但問題是我不明白它究竟是如何工作的,我沒有很長時間學習Java,for循環(「int count:base」)究竟是什麼 – user1832483

+0

基本上它循環通過數組一個項目,將當前項目放置在左側聲明的變量中。因此for(int value:base)循環遍歷基本設置「value」到每個項目。谷歌「每個循環的Java」有更好的解釋:P – thedan

+0

不好看。 – user1832483

1

嘗試:

LinkedList<Integer> resList = new LinkedList<Integer>(); 
for(int i = 0 ; i < myArray.length ; ++i) { 
    int myInt = myArray[i]; 
    for(int j = 0 ; j < myInt ; ++j) { // insert it myInt-times 
     resList.add(myInt); 
    } 
} 
// TODO: build the result as an array : convert the List into an array 
0

試試這個:

int[] anArray = { 
    0, 1, 2 
}; 
int[] newArray = new int[100]; 
int cnt=0; 
for(int i=0; i<anArray.length; i++) 
{ 
    for(j=1;j>0;j--) 
    { 
     newArray[cnt]=anArray[i]; 
     cnt++; 
    } 
}