[英]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. 我正在尝试制作一个介于0到25之间的100个随机数的数组,并按奇数和偶数对它们进行排序,并显示两个结果数组。 (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.
(不允许使用列表。)运行此代码时,所有发生的事情都是一遍又一遍,大多数情况下都是0。
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]);}
}
You're using splitrandoms(array);
您正在使用
splitrandoms(array);
function in the Loop, you should call it out of the For Loop . 函数在循环中,您应该从For循环中调用它。 .
。 .
。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.