I want my program to "sort" an array into two different arrays. Meaning every value that is greater than or equal to 500 goes to the array values2. Every value that is less than 500 goes to the array values3.
My problem is that whatever I try its always the last value that matches the condition that is shown.
for (int i = 0; i < values.length && i < noOfNumbers; i++)
{
if (values[i] >= 500)
{
for (int k = 0; k < numbersAbove500; k++)
{
values3[k] = values[i];
}
}
else
{
for (int j = 0; j < numbersAbove500; j++)
{
values2[j] = values[i];
}
}
}
Typical Output
How many numbers do you wish the array to contain? 8
877 338 741 119 20 853 235 786
786 786 786 786
235 235 235 235
You only need a single loop. Your inner loops make no sense.
int j = 0;
int k = 0;
for (int i = 0; i < values.length && i < noOfNumbers; i++) {
if (values[i] >= 500) {
values3[k] = values[i];
k++;
} else {
values2[j] = values[i];
j++;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.