bri
bri

Reputation: 17

how to fill array with given values

i have to get a sequence of numbers and count how many times it takes and then put it into an array so i can sort the array and look for the 10th largest. I can get the count but cant seem to fill the array, i either put in the final count at every index in the array or i just increase the value of the array at index 0 to the count of all numbers, can anyone help.

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()
    {

    }
}

Upvotes: 0

Views: 193

Answers (2)

Edwin
Edwin

Reputation: 825

Try to change your main to this:

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] + ", ");
  }
}

Also change your arrayCounter method to this:

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

Upvotes: 3

Joshua
Joshua

Reputation: 2479

If you want to fill an array with a given value, use Arrays.fill, from the java.utils.Arrays class.

Upvotes: 0

Related Questions