2012-11-17 140 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++; 
    } 
}