如何使用给定值填充数组

时间:2014-10-19 16:02:13

标签: java arrays

我必须获得一系列数字并计算它需要多少次然后将它放入一个数组中,这样我就可以对数组进行排序并寻找第10大数字。我可以获得计数,但似乎无法填充数组,我要么在数组中的每个索引处放入最后的计数,要么我只是将索引0处的数组值增加到所有数字的计数,任何人都可以帮助。 / p>

public class seBuilder

{

//int count=0;


//int [] myArray= new int[10];


    public static void main (String args[])
    {
      int count=0;
      int [] myArray= new int[13];
      int z=0;
      for(int i=2;i<=myArray.length;i++)
      {
        z=valuegetter(i);
        System.out.println(z);

      }

      //arraycounter(myArray, z);


    }

    public static int valuegetter(int num)
    {
     int count=0;
     do// do while loop
     {
        //if its an odd number
        if(num%2==1){
            num=(num*3)+1;//do this from the question
            count++;// add one to count
        }
        //if num is 2 this will catch and make the code break out
        else if(num==2){
            //devide num by 2, this will give you 1 allways
            System.out.println(num/2);
            count++;//adds 1 again
        }
        else
        {
            num=num/2;//this will use if number is even
            count++;//adds one to count
        }

     }
      while(num>2);//the condition to jump out of loop
      //System.out.println("there are "+count+" sequences in that mumber");
     return count;
    }


    public static int[] arraycounter(int myArray[], int count)
    { 

      for(int i=0;i<=myArray.length-1;i++)
      {
          myArray[i]=count;
          System.out.println(" "+myArray[i]);
      }
      return myArray;
    }  

    public static int tenhigh()
    {

    }
}

2 个答案:

答案 0 :(得分:3)

尝试将您的主要内容更改为:

public static void main (String args[])
{
  int count=0;
  int [] myArray= new int[13];
  int z=0;
  for(int i=2;i<=myArray.length;i++) {
    z=valuegetter(i);
    System.out.println(z);
    arraycounter(myArray, z, i);

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

同时将arrayCounter方法更改为:

public static int[] arraycounter(int myArray[], int count, int i)
{ 
    int j = i - 2;
    myArray[j] = count;
    return myArray;
}

答案 1 :(得分:0)

如果要使用给定值填充数组,请使用Arrays.fill类中的java.utils.Arrays