I want to sort my array 'arrSort' auto generated with random value upto 2000 into 2 different arrays, 'arrEven' and 'arrOdd' and then print our the values with the array index number too for the odd and even arrays similar to the print output of the arrSort array.
I've had a look at this question Array even & odd sorting, and it's helpful, but doesn't address sorting an array with randomly generated variables and the 'for' loop used in a way that increasingly considers values in an array since the value are not already predefined.
I've been stuck at this for so long. Plz help.
public class ArraySortingOddEven
{
public static void main(String[] args)
{
Random rand = new Random();
int upperbound = 2000;
int n = 0;
// Create arrays (indexed).
int arrSort[];
arrSort = new int[20];
int arrEven[] = new int[10];
int arrOdd[] = new int[10];
{// Assign random numbers.
for (n = 0; n <= arrSort.length - 1; n++)
{
arrSort[n] = rand.nextInt(upperbound);
System.out.println("random value assigned for arrsort[" + n + "] is " + arrSort[n]);
}
}
System.out.println("");
for (n = 0; n < arrSort.length; n++)
{
if (arrSort[n] % 2 == 0)
{
arrSort[n] = arrEven[n];
} else
{
arrSort[n] = arrOdd[n];
}
n++;
}
for (n = 0; n < arrSort.length-1; n++)
{
System.out.println("Numbers in the even array are " + arrEven[n]);
n++;
}
System.out.println("");
for (n = 0; n < arrSort.length-1; n++)
{
System.out.println("Numbers in the odd array are " + arrOdd[n]);
n++;
}
}
}
Here is the console.
random value assigned for arrsort[0] is 679
random value assigned for arrsort[1] is 714
random value assigned for arrsort[2] is 493
random value assigned for arrsort[3] is 1798
random value assigned for arrsort[4] is 5
random value assigned for arrsort[5] is 1350
random value assigned for arrsort[6] is 527
random value assigned for arrsort[7] is 1839
random value assigned for arrsort[8] is 479
random value assigned for arrsort[9] is 886
random value assigned for arrsort[10] is 1554
random value assigned for arrsort[11] is 39
random value assigned for arrsort[12] is 1641
random value assigned for arrsort[13] is 1057
random value assigned for arrsort[14] is 514
random value assigned for arrsort[15] is 382
random value assigned for arrsort[16] is 1058
random value assigned for arrsort[17] is 1132
random value assigned for arrsort[18] is 503
random value assigned for arrsort[19] is 765
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10
at ArraySortingOddEven.main(ArraySortingOddEven.java:37)
Aucun commentaire:
Enregistrer un commentaire