Sort descending
I am a new programmer in java, use this site a lot to find out paths. Today I ran into another problem regarding the program I am making for practice.
I have an array:
final int EXAMS = 5;
int[] scores = new int [EXAMS];
The values ββfor this array are then requested from the user via the 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 create an ascending sort to sort the "score []" values:
Arrays.sort(scores);
System.out.println("The sorted int array is:");
for (int number : scores)
{
System.out.println("Number = "+ number);
}
But I want the sort to be in descending order. When I put
Arrays.sort(scores, Collections.reverseOrder());
I get the error "No suitable sorting method found." Please, help.
source to share
There is Arrays
no method in the class sort
that accepts int[]
a Comparator
. Methods sort
in the class Arrays
that accept Comparator
require an array of a reference type (while being int[]
an array of primitive type).
If you change the array type scores
from int[]
to Integer[]
, your code will work as the public static <T> void sort(T[] a, Comparator<? super T> c)
class method Arrays
will match your call Arrays.sort(scores, Collections.reverseOrder());
.
final int EXAMS = 5;
Integer[] scores = new Integer [EXAMS]; // the only required change
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();
}
}
Arrays.sort(scores, Collections.reverseOrder());
System.out.println("The sorted int array is:");
for (int number : scores) {
System.out.println("Number = "+ number);
}
source to share
There is no sorting method for arrays in java. But ArrayList has a sorting method. You can use the following code to sort the list in reverse order.
List l=new ArrayList();
l.add(5);
l.add(1);
l.add(2);
l.add(3);
Collections.sort(l,Collections.reverseOrder());
System.out.println(l);
source to share