I'm a new programmer to java, been using this website a lot to learn the ways. Today I've stumbled into another problem towards a program I'm doing for practice.
I have an array:
final int EXAMS = 5;
int[] scores = new int [EXAMS];
The values for this array are then asked from the user through a Scanner object:
for (int index = 0; index < EXAMS; index++)
{
System.out.println("Enter the score for " + (index+1) +":");
scores[index] = kb.nextInt();
if (scores[index] < 0){
System.out.println("The number you have entered is invalid.");
scores[index] = kb.nextInt();
}
}
I managed to make an ascending order sorting of the values "scores[]":
Arrays.sort(scores);
System.out.println("The sorted int array is:");
for (int number : scores)
{
System.out.println("Number = "+ number);
}
But I want the sorting to be in descending order. When I put the
Arrays.sort(scores, Collections.reverseOrder());
I get an error saying: "no suitable method found for sorting." Please help.
Collections.reverseOrder()
Won't work because the array is of primitive type. You can change from int to Integer or try something different like:
Arrays.sort(scores);
ArrayUtils.reverse(scores);
Your final option would be to make your own code.
The following works (using the Integer Objects instead of primitive int):
Integer[] test = {1, 2, 4, 3, 5};
Arrays.sort(test, Collections.reverseOrder());
System.out.println(Arrays.toString(test)); // [5, 4, 3, 2, 1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With