具有两个不同阵列的FIll阵列

时间:2013-12-24 09:53:58

标签: java

帮助我填充数组Final[],使数组Even[]的值存储在Final[]&的偶数索引上数组Odd[]填充Final[]个奇数索引..

public class Test 
    {

    public static void main(String[] args) 
        {
            A obj = new A();
            obj.run();
        }
    }

class A
{ 
    int temp, b;

    public void run(){

        Double[] ResultList = {1.1,2.2,3.33,4.1,5.0,6.7777};        //Dummy Values

        Double[] Final = new Double[ResultList.length];

        Double[] Even = {11.989898,22.545454,33.5454,44.444,55.5647,66.11111};  //Dummy Values

        Double[] Odd = {11.545454,22.5454,33.444,44.5647,55.989898,66.11111};   //Dummy Values

    for(int a = 0; a < ResultList.length ; a+=2)
    {   
        if(temp != 0)
        {   
            b = temp;

            System.out.println("Outer Temp B: "+temp+"\n");
        }

        for(b = 0; b <= a; b++)     //Want to stop this loop in a Manner That b=0,1,2,3,4...
        {           
            temp = b;       

            System.out.println("Inner Temp: "+b+"\n");

            Final[a] = Even[b];

            Final[a+1] = Odd[b];

            if(b != 0)              //Trying this to stop thsi loop from repetition
            {
                b = a+1;

                System.out.println("Inner B: "+b+"\n");
            }
        }
    }

    for(int i = 0; i < ResultList.length; i++)

        System.out.print(Final[i]+" ");
    }
}

需要输出:{11.989898, 11.545454, 22.545454, 22.5454, 33.5454, 33.444, 44.444, 44.5647, 55.5647, 55.989898, 66.11111, 66.11111}

2 个答案:

答案 0 :(得分:3)

我将如何做到这一点 -

public class A {
  int temp, b;

  public void run() {
    double[] even = { 11.989898, 22.545454, 33.5454,
        44.444, 55.5647, 66.11111 }; // Dummy Values

    double[] odd = { 11.545454, 22.5454, 33.444,
        44.5647, 55.989898, 66.11111 }; // Dummy Values
    double[] out = new double[even.length
        + odd.length];

    int count = 0;
    for (int i = 0; i < out.length; i += 2) {
      out[i] = even[count];
      out[i + 1] = odd[count];
      count++;
    }

    for (int i = 0; i < out.length; i++) {
      System.out.print(out[i] + " ");
    }
  }

  public static void main(String[] args) {
    A obj = new A();
    obj.run();
  }
}

哪个输出

11.989898 11.545454 22.545454 22.5454 33.5454 33.444 44.444 44.5647 55.5647 55.989898 66.11111 66.11111 

答案 1 :(得分:2)

你走了:

Double Final[] = new Double[Even.length + Odd.length];
for (int i = 0; i < Even.length; ++i) 
    Final[i*2] = Even[i]; // i*2 --> 0, 2, 4

for (int i = 0; i < Odd.length; ++i) 
    Final[i*2+1] = Odd[i]; // i*2+1 --> 1, 3, 5