user2229475
user2229475

Reputation: 9

What's wrong with this array evens and odds code?

I'm trying to make an array of 100 random numbers between 0 and 25, sort them by odds and evens, and display the two resulting arrays. (I'm not allowed to use lists.) When I run this code, all that happens is it goes over and over again, mostly spewing 0s.

public static void main (String [] args)
{
   int array[]= new int[100];

   for(int i=0;i<100;i++)
   { 
     double k=Math.random();
     k=k*25;
     k=Math.rint(k);
     array[i]=(int)k;

     splitrandoms(array);

   }
}
public static void splitrandoms(int array[])
{   
   int oddSize = 0; 
   int evenSize = 0; 
   for (int i = 0; i< array.length; i++) 
   {
      if (array[i] % 2 == 0) 
      {evenSize++;}
      else 
      {oddSize++;}
   }

   int oddArray[] = new int[oddSize];
   int evenArray[] = new int[evenSize];

   int even = 0;
   int odd = 0;

   for (int b = 0; b< 100; b++) 
   {
      if (array[b] % 2 == 0) 
      {evenArray[even++] = array[b];}
      else 
      {oddArray[odd++] = array[b];}
   }


   System.out.println("Evens:");
   for(int q = 0; q < evenSize; q++)
   {System.out.println(evenArray[q]);}

   System.out.println("Odds:");
   for(int f = 0; f < oddSize; f++)
   {System.out.println(oddArray[f]);}
}

Upvotes: 0

Views: 318

Answers (2)

Jilberta
Jilberta

Reputation: 2866

You're using splitrandoms(array); function in the Loop, you should call it out of the For Loop . . .

Upvotes: 1

NPE
NPE

Reputation: 500277

The problem is that you are calling the sorting function from within the loop that populates the original array. Move the following line outside the loop:

splitrandoms(array);

Upvotes: 0

Related Questions