-1

(Sort students) Write a program that prompts the user to enter the number of stu-dents, the students’ names, and their scores, and prints student names in decreas-ing order of their scores.

So I just solved this problem, but I think is a more efficient way to do so. For instance, I created 2 methods with one array each to create Scores and student´s names then another method to sort only the scores array but also in the same method, I created a new array to save the index of each value so it would match with the student´s names array when I printed in the main. Overall, there must be an easier way to solve this problem. Thanks!

1 Answers1

2

Define a class

You asked:

Overall, there must be an easier way to solve this problem.

Yes, there is… don't use separate arrays to track related data (generally).

If you are tracking a score for each student, you should be defining a class to represent that data. Java is an object-oriented language, so make use of objects!

record

Java 16 brings a new briefer way to define a class whose main purpose is to communicate data transparently and immutably: records.

You merely need to define the type and names of the member fields.

public record Scoring ( String studentName , int score ) {}

For a record, the compiler implicitly creates the constructor, getters, equals & hashCode, and toString.

Collect instances of your class in a List or Set.

int initialCapacity = 3 ;  // Specify how many elements do you expect to use.
List< Scoring > scorings = new ArrayList<>( initialCapacity ) ;
scorings.add( new Scoring( "Alice" , 98 ) ) ;
scorings.add( new Scoring( "Bob" , 88 ) ) ;
scorings.add( new Scoring( "Carol" , 77 ) ) ;

Or your classwork may be focused on using arrays rather than Java Collections.

Scoring[] scorings = new Scoring[ 3 ] ;
scorings[ 0 ] = new Scoring( "Alice" , 98 ) ;
…

As for gathering input from the user via the console, search Stack Overflow to see many existing Questions and Answers on using Scanner class.

As for sorting a collection of objects by one of the properties of that class, search Stack Overflow to see many existing Questions and Answers using Collections.sort while passing an implementation of Comparator. Such as How to sort List of objects by some property, How do I sort a list by different parameters at different timed, and How to sort an arraylist of objects by a property?.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154