java - find the max value from a linked list - java

Disclaimer: I am a very early student and am struggling to learn java. Please tell me if I'm leaving out any important information.
I am writing a program that prompts the user to do various operations to a linked list (add, remove, change value, etc.) but rather than storing a string or some primitive data type I am storing objects of type Student (which basically contains a string for the name of the student and an integer for their test score) and am stuck on how to find the maximum test score since I can't just find the highest Student.
Any help would be appreciated.

Well you can have two variables, one as the currentScore, and another as the newScore. And then traverse through each student object, get the test value, and then compare. If the new score is lower, then keep current. If new score is higher, replace current score with new score, and keep traversing. When you traverse the list, you have the highest score

You can iterate over the list as other answers described or you can use Collections.max method. To use this method your Student class should implement comperable interface.
public class Student implements Comparable<Student>
and you need to add compareTo method to the class:
#Override
public int compareTo(Student student)
{
if (this.score > student.score)
{
return 1;
}
if (this.score < student.score)
{
return -1;
}
else
{
return 0;
}
}
Now when you write Collections.max(list) you will get the Student with the highest score.

I wrote a simple program that matched your case.
Main Class:
import java.util.*;
import java.lang.Math;
public class FindHighestScore
{
public static void main(String[] args)
{
LinkedList<Student> studentLinkedlist = new LinkedList<Student>();
studentLinkedlist.add(new Student("John",1)); // Adding 5 students for testing
studentLinkedlist.add(new Student("Jason",5));
studentLinkedlist.add(new Student("Myles",6));
studentLinkedlist.add(new Student("Peter",10)); // Peter has the highest score
studentLinkedlist.add(new Student("Kate",4));
int temp = 0; // To store the store temporary for compare purpose
int position = 0; // To store the position of the highest score student
for(int i = 0; i < studentLinkedlist.size(); i ++){
if(studentLinkedlist.get(i).getScore() > temp){
temp = studentLinkedlist.get(i).getScore();
position = i;
}
}
System.out.println("Highest score is: " + studentLinkedlist.get(position).getName());
System.out.println("Score: " + studentLinkedlist.get(position).getScore());
}
}
The student constructor class:
public class Student
{
String name;
int score;
Student(){
}
Student(String name, int score){
this.name = name;
this.score = score;
}
String getName(){
return this.name;
}
int getScore(){
return this.score;
}
}
The above program produce result as follows:
Highest score is: Peter
Score: 10

Related

Index out of bounds for an array (java)

My code is supposed to print out the student with the highest range. There is a method in my Student class which calculates the range, while in my Classroom class there is another method that determines which student had the highest growth. My problem comes in the class Student, I get an Out of Bounds Exception in the addExamScore method.
Main class:
public class ClassroomTester
{
public static void main (String[] args)
{
Classroom c = new Classroom(2);
Student ada = new Student("Ada", "Lovelace", 12);
ada.addExamScore(44);
ada.addExamScore(65);
ada.addExamScore(77);
Student alan = new Student("Alan", "Turing", 11);
alan.addExamScore(38);
alan.addExamScore(24);
alan.addExamScore(31);
c.addStudent(ada);
c.addStudent(alan);
c.printStudents();
Student mostImproved = c.getMostImprovedStudent();
System.out.println("The most improved student is " + mostImproved.getName());
}
}
Student class:
public class Student
{
private static final int NUM_EXAMS = 4;
private String firstName;
private String lastName;
private int gradeLevel;
private double gpa;
private int[] exams;
private int numExamsTaken;
public Student(String fName, String lName, int grade)
{
firstName = fName;
lastName = lName;
gradeLevel = grade;
exams = new int[numExamsTaken];
numExamsTaken = 0;
}
public int getExamRange()
{
int maximum = 0;
int minimum = 0;
for(int i = 0; i < exams.length; i++){
if(exams[i]<exams[minimum]){
minimum = i;
}
else if(exams[i]>exams[maximum]){
maximum = i;
}
}
return exams[maximum]-exams[minimum];
}
public String getName()
{
return firstName + " " + lastName;
}
public void addExamScore(int score)
{
exams[numExamsTaken] = score;
numExamsTaken++;
}
public void setGPA(double theGPA)
{
gpa = theGPA;
}
public String toString()
{
return firstName + " " + lastName + " is in grade: " + gradeLevel;
}
}
First, you're initializing exams in the constructor the line before you initialize numExamsTaken, the order should be reversed because you need to know what numExamsTaken is before using it. I'd recommend storing the maximum and minimum as scores instead of indexes but that's just personal preference I think it makes the code more readable, so up to you. The index out of bounds problem probably has to do with your addExamScore method. If you've taken 4 exams it might look like [90, 85, 74, 82] where the indexes are 0, 1, 2, 3 and numExamsTaken = 4. Indexes starting at 0 is called zero-indexing and is used in most if not all programming languages.
exams[3] = 82 and exams[4] is going to give you an out of bounds error. Since you're not using an arrayList every time you want to add an element you're going to need to create an empty array of one size bigger than your current array, copy the previous scores over, and slide the new score into the last slot (in the case above would be index 4, which isn't out of bounds in the new array). Store your new array where your old array was in exams[].
Index out of bounds exception shows when array crosses it limits to store the value.
You have declared array of size '0' inside the constructor
in the line exams = new int[numExamsTaken];
initialize the size of the array with your expected range or use ArrayList to add values without specifying the size in prior
The problem with your code here is that you are trying to access a value in an array, which has not been allocated there. This is why the output is giving a ArrayIndexOutOfBoundsException, since you are trying to access an index in an array that is out of bounds of the array. In Java, arrays are fixed in size, meaning once you call new on an array, you cannot change the size of it without calling new on another array with a different size. In this case, it will be easiest to use a List, like an ArrayList, which does all of the resizing, copying, etc. for you, so you can use it as if it were a dynamically sized array. Your code would change to look something like this:
public class Student
{
// ...
private List<Integer> exams;
// ...
public Student(String fName, String lName, int grade)
{
// ...
exams = new ArrayList<>();
// ...
}
public int getExamRange()
{
int maximum = 0;
int minimum = 100;
for(int i = 0; i < exams.length; i++){
if (exams.get(i) > maximum) {
maximum = exams.get(i);
}
if (exams.get(i) < minimum) {
minimum = exams.get(i);
}
}
return maximum - minimum;
}
public void addExamScore(int score)
{
exams.add(score);
numExamsTaken++;
}
}
You can look more into List and ArrayList documentation at the java API website. Also, your logic for getting the minimum element is not correct, since if you have no scores that are less than 0, it will always assume that the minimum score is 0. You can fix this by setting the initial value to 100(the maximum possible value of a test score), or using another method that you prefer.

How to sort map without using comparable and Comparator Interface? How to write Custom Sorting?

Problem - I have a Student class, it contains Name, roll number, three subject marks m1,m2,m3, and total marks. I need to sort Student object according to their total marks if two or more students marks are equal then sort it according to their name. Note - I have to google it but not getting expected solution in stackoverflow question every one using Comparable and Comparator interface.
I have created class Studnt
public class Student {
private String name;
private Integer rollNumber;
private int m1;
private int m2;
private int m3;
private int totMarks;
//Getter setter
}
Main class
public class StudentData {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enetr the number of Student");
int totalStudent = sc.nextInt();
Map<Integer,Student> map = new TreeMap<Integer,Student>();
for(int i =0;i<totalStudent;i++) {
Student ss = new Student();
System.out.println("Enter the Student roll number");
ss.setRollNumber(sc.nextInt());
System.out.println("Enter the Student Name");
ss.setName(sc.next());
System.out.println("Enter the m1 marks ");
ss.setM1(sc.nextInt());
System.out.println("Enetr the m2 marks ");
ss.setM2(sc.nextInt());
System.out.println("Enter the m3 marks ");
ss.setM3(sc.nextInt());
ss.setTotMarks(ss.getM1()+ss.getM2()+ss.getM3());
map.put(ss.getTotMarks(),ss);
ss=null;
}
//stdList.forEach(System.out::print);
for(Map.Entry<Integer,Student> m :map.entrySet()) {
System.out.println(m);
}
}
}
Actually, I am using TreeMap it sort the value by key(total marks is key in my TreeMap). but two or more students have equal marks. Then older student object (value) replaced by the new student because of Key not allowed duplicate
output
6=Student [name=ved, rollNumber=12, m1=2, m2=2, m3=2, totMarks=6]
9=Student [name=prakash, rollNumber=56, m1=3, m2=3, m3=3, totMarks=9]
the only unique totMarks stored in the map
Since you can't use existing Comparator or sorting algorithms, you need to do it on your own. I have implemented a static function lessOrEqual which accepts 2 Student instances, compares them and returns whether or not s1 is less or equal to s2. larger(Student s1, Student s2) which returns true ONLY IF s1 is larger than s2. There can be many different ways of doing this, it's really up to you as it's just a comprison. The function first checks the grades, if the grades match, it will then check the name and return accordingly.
EDIT: As you can see I replaced lessOrEqual with larger since the selection sort I'm using needs to find larger. It's the same effect, I only did it for better readability of the sort.
Then I implemented another static function that accepts ArrayList<Student>, sorts it and returns it sorted. The sorting algorithm used is very basic: Selection sort. It's O(N^2) which isn't efficient, but I did it for the sake of simplicity in the demo below.
Code:
import java.util.ArrayList;
public class Student {
private String name;
private Integer rollNumber;
private int m1;
private int m2;
private int m3;
private int totMarks;
public static boolean larger(Student s1, Student s2){
if(s1.totMarks < s2.totMarks) return false;
else if (s1.totMarks > s2.totMarks) return true;
// compare names
else return s1.name.compareTo(s2.name) > 0;
}
public static ArrayList<Student> sortSelection(ArrayList<Student> list){
for(int i=0; i<list.size(); i++){
for(int j=i+1; j< list.size(); j++){
if(larger(list.get(i), list.get(j))){ // swap
Student temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
}
}
}
return list;
}
//Getter setter
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getTotMarks(){
return totMarks;
}
public void setTotMarks(int totMarks){
this.totMarks = totMarks;
}
#Override
public String toString(){
return String.format("Name: %20s - Total Marks: %3d", name, totMarks);
}
public static void main(String[] args){
Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();
Student s4 = new Student();
s1.setName("John Smith");
s1.setTotMarks(98);
s2.setName("Jack Smith");
s2.setTotMarks(98);
s3.setName("Adam Noob");
s3.setTotMarks(100);
s4.setName("Ved Parkash");
s4.setTotMarks(99);
ArrayList<Student> list = new ArrayList<>();
list.add(s4);
list.add(s3);
list.add(s1);
list.add(s2);
System.out.println("Array before sorting:");
for(int i=0; i<list.size(); i++){
System.out.println(list.get(i).toString());
}
Student.sortSelection(list);
System.out.println("Array after sorting:");
for(int i=0; i<list.size(); i++){
System.out.println(list.get(i).toString());
}
}
}
Output:
Array before sorting:
Name: Ved Parkash - Total Marks: 99
Name: Adam Noob - Total Marks: 100
Name: John Smith - Total Marks: 98
Name: Jack Smith - Total Marks: 98
Array after sorting:
Name: Jack Smith - Total Marks: 98
Name: John Smith - Total Marks: 98
Name: Ved Parkash - Total Marks: 99
Name: Adam Noob - Total Marks: 100
Notes:
1) See the order of addition of Students into the list, it's 4,3, 1 then 2. This is to prove that it sorts according to name when the grades match (Jack Smith vs John Smith).
2) I hardcoded the students to make for a better demo.
3) As you may notice, I'm not setting any of the other variables since the question is solely about sorting, and the only contributing variables to sorting are: name and totMarks. You will have to do the rest.
4) I am using ArrayList, but this isn't limited to that, with simple changes you can use it on a normal Student[] array.
5) The function larger doesn't have to be static, you can make it a member function and use it differently. For example, the code above would change to:
public boolean larger(Student other){
if(totMarks < other.totMarks) return false;
else if (totMarks > other.totMarks) return true;
// compare names
else return name.compareTo(other.name) > 0;
}
public static ArrayList<Student> sortSelection(ArrayList<Student> list){
for(int i=0; i<list.size(); i++){
for(int j=i+1; j< list.size(); j++){
// comparison way changes accordingly
if(list.get(i).larger(list.get(j))){ // swap
Student temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
}
}
}
return list;
}
In the interests of Keeping it simple (i.e. the KISS principle) and explaining my "hint" relating to a compound key, following is the worked example.
The "key" to the solution is to let the tree sort the data naturally (not, IMHO, to add to the code making it more complex by providing a manual sort). Thus the student class needs to return a key that the tree can naturally sort.
To produce the desired sort result, the key for the Tree is (total Marks, student name).
Here is the revised Student class (minus getters and setters, but I did add a new constructor to make life easy for me):
public class Student {
private String name;
private Integer rollNumber;
private int m1;
private int m2;
private int m3;
private int totMarks;
//Getter setter
public Student() {
}
public Student(String name, Integer rollNumber, int m1, int m2, int m3) {
this.name = name;
this.rollNumber = rollNumber;
this.m1 = m1;
this.m2 = m2;
this.m3 = m3;
this.totMarks = m1 + m2 + m3;
}
public String getKey() {
// return String.format("%d-%s", totMarks, name); // WRONG!
return String.format("%04d-%s", totMarks, name); // Right
}
public String toString() {
return String.format("%06d: %s - %d", rollNumber, name, totMarks);
}
}
Note there is a commented out line of code in the getKey method with the comment WRONG. This relates to my hint of testing with single digit scores. Try swapping out the two lines of code to see the correct and incorrect result.
Here is the main, I removed all of the Scanner stuff - again to make life easy for me. Hopefully you can follow it and add back in your scanner loop.
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class StudentData {
public static void main(String[] args) {
// Initialise a list of students (as I don't want to rekey all the details each
// time I run the program).
List<Student> studentList = Arrays.asList(
new Student("Fred", 1, 2, 2, 2), /* Score of 6 */
new Student("John", 2, 2, 3, 3), /* Score of 8 */
new Student("Jane", 3, 20, 25, 30), /* Score of 75 */
new Student("Julie", 4, 20, 15, 10) /* Score of 45 */
// add as many new students as you like, and reorder them
// as much as you like to see if there is any difference in the
// result (there shouldn't be).
);
// Note the key of the tree is of type String - not Integer.
// This is the heart of the algorithm, the tree will be "sorted"
// on the natural key provided. This "natural key" is in fact
// a compound key that is generated by combining the total score
// and the student name.
Map<String,Student> map = new TreeMap<String,Student>();
for (Student ss : studentList) {
map.put(ss.getKey(),ss);
}
//stdList.forEach(System.out::print);
for(Map.Entry<String,Student> m :map.entrySet()) {
System.out.println(m);
}
}
}
I hope you agree that this is a simpler solution. There is also a potential performance benefit as the students are sorted as they are being loaded into the tree (i.e. once). The performance of this sorting is, I think, log(n). Sort on retrieval will likely be n log(n) or worse.
Instead of storing the values as student store them as a map of (name, student), so that when a student with the same marks is encountered, it is added to the map.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enetr the number of Student");
int totalStudent = sc.nextInt();
Map<Integer, Map<String, Student>> map = new TreeMap<>();
for(int i =0;i<totalStudent;i++) {
Student ss = new Student();
System.out.println("Enter the Student roll number");
ss.setRollNumber(sc.nextInt());
System.out.println("Enter the Student Name");
ss.setName(sc.next());
System.out.println("Enter the m1 marks ");
ss.setM1(sc.nextInt());
System.out.println("Enetr the m2 marks ");
ss.setM2(sc.nextInt());
System.out.println("Enter the m3 marks ");
ss.setM3(sc.nextInt());
ss.setTotMarks(ss.getM1()+ss.getM2()+ss.getM3());
Integer key = ss.getTotMarks();
if (map.get(key) == null){ // if this is a new key in the map, then create a new TreeMap and put it
final TreeMap<String, Student> nameAndStudentMap = new TreeMap<>();
nameAndStudentMap.put(ss.getName(), ss);
map.put(key, nameAndStudentMap);
}else { // if the key already existed, then get the map stored and add to it.
map.get(key).put(ss.getName(), ss);
}
}
//stdList.forEach(System.out::print);
for(Map.Entry<Integer,Map<String, Student>> m :map.entrySet()) {
for (Map.Entry<String, Student> nameAndStudent : m.getValue().entrySet()) {
System.out.println(m.getKey() + " = " + nameAndStudent.getValue());
}
}
}

Java cycling through objects

I'm trying to cycle through objects and update a variable each time, I have a Player class that has all of the following variables:
Name, s1 ,s2, s3,...., s11, total
I want to go through each variable from the start to the end and adding the score at each go for each player (all the players are in an array list).
I'm not sure what the best way to do this is, is there a way to select a specific object and then add the variable depending on who go it is.
if you need any more information please ask and thanks in advance for any help given.
public void addScore(int turn, int score){
Player.setScore( turn, score);
}
You can cycle in array list with a simple for, like this:
ArrayList<Player> players = ...;
for (int i = 0; i < players.size(); i++) {
/*Operations on players[i] = the current player*/
}
To take and modify the variables of your player you can create getter and setter methods for each parameter like this:
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
If you have a lot of variables (s1, s11) of the same type, use an array:
int[] scores = new int[11];
So you can use another for cycle.
If I understand this question correctly, each player has a name, 11 scores, and a total. You seem to be asking how to iterate through a list of players and make the total equal to the sum of the 11 scores.
A more usual (in an OO language) approach would be just to ensure that the total is always equal to the sum of the 11 scores. (This is called "encapsulation", and is the fundamental idea behind all of object-oriented programming.) This is very easy to accomplish (for ease of programming, I put the scores in an array):
public class Player {
private String name ;
private int[] scores ;
private int total ;
public Player(String name) {
this.name = name ;
this.scores = new int[11] ; // all initialized to zero, as is total.
}
public void setScore(int whichScore, int score) {
int change = score - scores[whichScore] ;
scores[whichScore] = score ;
total = total + change ;
}
public int getScore(int whichScore) {
return scores[whichScore] ;
}
public int getTotal() {
return total ;
}
public String getName() {
return name ;
}
public void setName(String name) {
this.name = name ;
}
}
Now your question is redundant: the total is always equal to the sum of the scores, so there is no need to iterate through the players to compute the total anywhere in your code. You can get the total for each player with
for (Player p : listOfPlayers) {
System.out.println("Player "+p.getName()+" has total score "+p.getTotal());
}

JAVA Inheritance student, undergrad and gradstudent code

For a class project I was asked to create three codes.
Student Class
First, the student class containing three Parameters.
Name(String)
TestScores( int array),
Grade(String).
An empty Constructor. sets the Name and Grade to empty Strings. The TestScores Array will be initialised with three zeros.
Another Constructor(String n, int[] tests, String g)- This will set the name, testScores, and grade.
Three methods:
getName() to return the name
getGrade() to return the grade
setGrade() to set grade
getTestAverage() to return the average of the test scores.
This is where I am having difficulty The method computeGrade(), which, if the average is greater than or equal to 65, the grade is a "Pass". Otherwise it is a "Fail".
The second class is called UnderGrad. This class is a subclass of Student.
We had to create an empty Constructor and another Constructor (String n, int[] tests, String g).
We were instructed to override the computeGrade() method so that an UnderGrad() student must get a 70 or higher to pass.
The third class is the GradStudent a subclass of Student.
We have to create 1 instance variable, int MyGradID, and an empty constructor, which calls super, and set the IDs to 0.
And another constructor (String n, int[] tests, String g, int id)- Remember to call the super constructor and set ID.
Again where I am having challenges. We had to write the method getId(), to return the ID number. Again we needed to override the computeGrade() method And, if the average is greater than or equal to 65, the grade is a "Pass". Otherwise it is a "Fail". But if the test average is higher than 90, the grade should be "Pass with distinction".
I have great difficulty with this task. I attached the GradStudent code. Can you find the errors please? I don't fully understand how to override the superclass private instance variables.
public class GradStudent extends Student {
private int MyGradID;
public void GradStudent() {
super();
MyGradID = 0;
}
public void GradStudent(String n, int[] tests, String g, int id) {
super(n, tests, g);
MyGradID = id;
}
public int getId() {
return MyGradID;
}
#Override public void computeGrade() {
if (testScores.getTestAverage() >= 65) {
super.setGrade("Pass");
} else if (testScores.getTestAverage() > 90) {
grade = "Pass with distinction";
}
}
}
This is my Student class. I'm not sure if I am referencing my super class correctly, so I am adding it. Hopefully you can explain it to me.
public class Student {
private String name;
private int[] testScores = new int[3];
private String grade;
public Student() {
name = "";
grade = "";
testScores[0] = 0;
testScores[1] = 0;
testScores[2] = 0;
}
public Student(String n, int[] tests, String g) {
name = n;
testScores = tests;
grade = g;
}
public String getName() {
return name;
}
public String getGrade() {
return grade;
}
public void setGrade(String newGrade) {
grade = newGrade;
}
public int getTestAverage() {
int average = 0;
int count = 0;
for (int testScore : testScores) {
count++;
average = average + testScore;
}
return average / testScores.length;
}
public void computeGrade() {
grade = "Fail";
if (this.getTestAverage() >= 65) {
grade = "Pass";
}
}
}
This question simply wouldn't exist if you had an IDE (or, looked at the feedback from compile). I pasted the code into Eclipse and out popped a lot of problems.
Let's look at GradStudent.
public class GradStudent extends Student {
private int MyGradID;
// Constructors do not return anything.
public GradStudent() {
super();
MyGradID = 0;
}
// Again, constructors do not return anything.
public GradStudent(String n, int[] tests, String g, int id) {
super(n, tests, g);
MyGradID = id;
}
public int getId() {
return MyGradID;
}
// Okay. Override annotation in place. Now, computeGrade() needs to get its data from someplace. Fortunately, we
// have a method in Student to do that for us. That method is called 'getTestAverage()'. You do not need to
// reference the array created in 'Student'.
#Override public void computeGrade() {
int testAverage = getTestAverage();
if (testAverage >= 65) { // Evaluate against that testAverage. There is no method (or parameter) associated
// with an array that will compute its average.
setGrade("Pass");
} else if (testAverage > 90) {
setGrade("Pass with distinction");
}
}
}
The Student class is just fine (though count in getTestAverage() is a pointless variable which doesn't do anything and an int[] is created with all values being initialised to 0).
Now I would question why the instructor would have told you to create a constructor to set the grade... when you don't actually know what the grade is... but whatever.
Where are you having trouble with the computeGrade() method in Student? It seems fine to me. The problem in GradStudent is fixed given the changes made above.
What jumps out at me is
if(testScores.getTestAverage>=65)
Try changing that to
if(testScores.getTestAverage()>=65)
Easy mistake to make. Hope this helps!
Edit - I see that twice.
Also, I don't think constructors should have a return type void (or any) though I could be wrong.

Sorting Multiple ArrayLists Advice?

Hey there guys and gals.
Background:
I'm working on a high score program for homework that asks for 5 names and 5 scores. After the names with the corresponding scores are entered the program sorts the two ArrayLists by highest score. Finally it displays the names with their scores in sorted order.
Question:
I'm having the devil of a time trying to sort the ArrayLists , do you any advice on sorting ArrayLists ?
Code:
import java.util.*;
public class Assignment6
{
public static void main(String args[])
{
ArrayList<String> names = new ArrayList();
ArrayList<Integer> scores = new ArrayList();
initializeArrays(names, scores);
//sortArrays(names, scores);
displayArrays(names, scores);
}
public static void initializeArrays(ArrayList names, ArrayList scores)
{
Scanner in = new Scanner(System.in);
for(int i=0; i<5; i++)
{
System.out.println("Enter the name for score # " + (i+1) + ": ");
names.add(in.next());
System.out.println("Enter the score for score # " + (i+1) + ": ");
scores.add(in.next());
}
}
public static void sortArrays(ArrayList names, ArrayList scores)
{
for(int i=0; i<5; i++)
{
if(scores[i] < scores[i+1])
{
Collections.swap(scores,a, b);
Collections.swap(names,a, b);
}
}
}
public static void displayArrays(ArrayList names, ArrayList scores)
{
System.out.println("Top Scorers: ");
System.out.println(names);
System.out.println(scores);
}
}
Create one object with fields: name and score with implements Comparable.
Then having ONLY one ArrayList use Collections.sort(list);
You can wrap both score and name into one object and store it in a list.
class Result implements Comparable<Result>{
private String name;
private int score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
#Override
public int compareTo(Result other) {
return this.score - other.score;
}
}
Now you can use Collections.sort(List<Result>) to sort them out based on the highest score.
ok, do you want to print something like that A-{Bob, Alex, ...}, where Bob is a name and A is scope, you can do it using one object as described by Alex, but if its home work I think your teacher want to see some comuter science data structure, in that case is Associative_array will be better. You can implement it by your side or use java implementation. Java provide us Map [T, V] , and implementation, for your case is TreeMap, where T - is scope and V - is a List of the Name because a lot of people can have the same scope.
So, result structure will be like that
Map<String, List<String>> sortedScopes = new TreeMap<>();
and using :
List<String> names = sortedScopes.get(scope);
if(names == null){
names = new ArrayList<>();
sortedScopes.put(scope, names);
}
names.add(name)
In that solution you will have just a 2 methods initialize and display,
Sorting by scope will execute on demand

Categories

Resources