I have a text file which looks something like this:
6
3.3 John Rodgers
3.9 Jim Braash
3.5 Kathy Calderon
3.2 Steve Hernandez
2.4 Stacy Lu
2.8 Faith Simmons
I've already written a Student class, which has basic functions:
package com.company;
public class Student {
private String firstName;
private String lastName;
private double grades;
public Student(String firstName, String lastName, double grades) {
this.firstName = firstName;
this.lastName = lastName;
this.grades = grades;
}
#Override
public String toString() {
return lastName + ", " + firstName + ", " + grades;
}
#Override
public boolean equals(Object obj) {
if(obj == null){
return false;
}
Student other = (Student) obj;
if (other.firstName.equals(this.firstName) && other.lastName.equals(this.lastName) && other.grades == this.grades) {
return true;
} else {
return false;
}
}
public String getFirstName() {
return this.firstName;
}
public String getLastName() {
return this.lastName;
}
public double getGrade() {
return this.grades;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setGrades(double grades) {
this.grades = grades;
}
}
And this is my Main class:
package com.company;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Student[] s = initialize();
Student max = maxIndex(s);
Student min = minIndex(s);
double avg = avg(s);
flush(max, min, avg);
}
public static void flush(Student max, Student min, double avg) throws FileNotFoundException {
DecimalFormat df = new DecimalFormat("#.#");
double avgFormatted = Double.parseDouble(df.format(avg));
PrintWriter writer = new PrintWriter("final.txt");
writer.write("Highest: " + max);
writer.write("\n");
writer.write("Lowest: " + min);
writer.write("\n");
writer.write("Average GPA: " + avgFormatted);
writer.close();
}
public static Student[] initialize() throws FileNotFoundException {
Scanner reader = new Scanner(new File("data.txt"));
int size = reader.nextInt();
Student[] students = new Student[size];
int index = 0;
while (reader.hasNextLine()) {
double grades = reader.nextDouble();
String firstName = reader.next();
String lastName = reader.next();
Student student = new Student(firstName, lastName, grades);
students[index] = student;
index++;
}
return students;
}
public static double avg(Student[] students) {
double avg = 0;
double sum = 0;
for (int i = 0; i < students.length; i++) {
sum += students[i].getGrade();
avg = sum / students.length;
}
return avg;
}
public static Student maxIndex(Student[] students) {
int max = 0;
for (int i = 1; i < students.length; i++) {
if (students[i].getGrade() > students[max].getGrade()) {
max = i;
}
}
return students[max];
}
public static Student minIndex(Student[] students) {
int min = 0;
for (int i = 1; i < students.length; i++) {
if (students[i].getGrade() < students[min].getGrade()) {
min = i;
}
}
return students[min];
}
}
So, my question involves dealing with the file. Let's say I added the name Jim Braash again into my file without changing the integer at the top. So my file looks like this:
6
3.3 John Rodgers
3.9 Jim Braash
3.9 Jim Braash
3.5 Kathy Calderon
3.2 Steve Hernandez
2.4 Stacy Lu
2.8 Faith Simmons
Even though there are 7 lines, there are still only 6 students because one is repeated. I already implemented the equals() method in my Student class, but I am unable to figure out how I would skip the line in the main() method and still have the same results as before. Thanks.
Use HashSet<Student> instead of Student[] and override hascode to conform to your equals. You won't have any duplicates any more.
Be aware that you can cause serious problems with wrong implementations of equals and hashcode. Properties that are used in this methods shouldn't be modified. This would cause possible duplicates and/or that you may not be able to accesss or remove the modified element in a HashSet.
The other answers have good ideas. But, if you just want a simple way to do it using your equals() method from your Student class, you could try the following for your initialize() method:
public static Student[] initialize() throws FileNotFoundException {
Scanner reader = new Scanner(new File("data.txt"));
int size = reader.nextInt();
Student[] students = new Student[size];
int index = 0;
while (reader.hasNextLine()) {
double grades = reader.nextDouble();
String firstName = reader.next();
String lastName = reader.next();
Student student = new Student(firstName, lastName, grades);
boolean duplicate = false;
for (int i = 0; i < students.length; i++) {
if (student.equals(students[i])) {
duplicate = true;
break;
}
}
if (!duplicate) {
students[index] = student;
index++;
}
}
reader.close(); // <--- Make sure to close the Scanner
return students;
}
Let me know if this works for you.
Instead of array of Student, try use Set of student
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.
This data type have only unique item.
EDIT 1
With array
while (reader.hasNextLine()) {
Double grades = Double.valueOf(reader.next());
String firstName = reader.next();
String lastName = reader.next();
Student student = new Student(firstName, lastName, grades);
if (Arrays.stream(students).noneMatch(s -> student.equals(s))) {
System.out.println(student);
students[index] = student;
index++;
}
}
EDIT 2
You can replace max, min, avg calculation with streams
public static void main(String[] args) throws FileNotFoundException {
Student[] s = initialize();
Student max = Arrays.stream(s).max(Comparator.comparing(student -> student.getGrade())).orElse(null);
Student min = Arrays.stream(s).min(Comparator.comparing(student -> student.getGrade())).orElse(null);
double avg = Arrays.stream(s).map(student -> student.getGrade()).reduce(0d, (x,y) -> x + y).doubleValue() / s.length;
flush(max, min, avg);
}
Related
I've been struggling a couple days now attempting to write this code. Basically,we have to perform a binarySearch based on the SSN of Comparable "Student" objects in a Student array. After performing the binarySearch on the SSN, the student who is associated with that SSN's first and last name should print out. I am finding difficulty in writing the binarySearch.
Here's my code so far: my Student class:
public class Student implements Comparable<Student>{
private String firstName, lastName, SSN, bankAccount;
public Student(String first, String last, String ssn, String bkacct) {
this.firstName = first;
this.lastName = last;
this.SSN = ssn;
this.bankAccount = bkacct;
}
//toString method
public String toString() {
return "Employee: [FirstName = " + firstName + ", LastName = " + lastName + ", SSN = " + SSN + ", BankAccount = "
+ bankAccount + "]";
}
public boolean equals(Object other) {
return (lastName.equals(((Student)other).getLastName()) &&
firstName.equals(((Student)other).getFirstName())&&
SSN.equals(((Student)other).getSSN()) &&
bankAccount.equals(((Student)other).getBankAccount()));
}
//Sorting the array based on SSN
public int compareTo(Student target) {
int result;
if (lastName.equals(target.getLastName()))
result = SSN.compareTo((String) target.getSSN());
else
result = SSN.compareTo((String) target.getSSN());
return result;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Object getSSN() {
return SSN;
}
public String getBankAccount() {
return bankAccount;
}
and my class where i perform my binarySearch:
public class ObjectBubbleSortTest {
//setting up binarySearch to find Array
public static <Student extends Comparable<Student>> int binarySearch(Student[] student, Student target) {
int low = 0;
int high = student.length - 1;
int middle = (low+high + 1)/2;
int location = -1;
while((low <= high) && (location == -1)) {
if (student[middle].compareTo(target) == 0 ) {
location = middle;
}
else if (student[middle].compareTo(target) < 0) { //middle element too high
high = middle - 1;
}
else {
low = middle + 1;
}
middle = (low + high + 1)/2;
}
return location;
}
public static void main(String[] args) {
//EMPLOYEES OF BURGER KING
Student[] student = new Student[5];
//order: First Name, Last Name, SSN, Bank_Account_Number
student[0] = new Student("Adam", "Sarrone", "1234567", "9022345");
student[1] = new Student("Ryan", "Petrowvoksi", "4345123", "0120345");
student[2] = new Student("Jenn", "Henderson", "8124512", "564214");
student[3] = new Student("Ricky", "Jean", "3512345", "612345");
student[4] = new Student("Dare", "Ogun", "421451", "198213");
System.out.println("Original array order: \n");
for (Student element : student)
System.out.print(element + "\n");
ObjectBubbleSorter.bubbleSort(student);
System.out.println();
System.out.println("\nSorted array order: \n");
for (Student element : student)
System.out.print(element + "\n");
System.out.println();
//need helping figuring out why the binary search is not printing out
int studentName = binarySearch(student, "421451");
System.out.print(studentName);
}
}
``
I am also getting an error on "int studentName = binarySearch" stating The method binarySearch(Student[], Student) in the type ObjectBubbleSortTest is not applicable for the arguments (Student[], String). I understand what it means but struggling to make my binarySearch adaptable to fix that error.
Any help would be greatly appreciated. Thank you.`
So, I was wondering if there is any way to get the Highest Name without using Names[5] ?
int[] points = { 68, 87, 91, 30, 56, 99, 91 };
String[] Names = { "Billon", "Bob", "Barbie", "Beny", "Bardon", "Becks", "Benji" };
showHighest(scores, Names);
int a = findThatName(Names, "Benji");
if (a == -1)
System.out.print("\nBenji is not on the list");
else
System.out.printf("\nName: %s had %s points", Names[a], points[a]);
a = findThatName(Names, "Fed");
if (a == -1)
System.out.print("\nFed was not on the list");
else
System.out.printf("\nName: %s had %s points", Names[a], points[a]);
}
public static void showHighest(int[] points, String[] Names) {
int max = points[0];
for (int a = 1; a < points.length; a++) {
if (points[a] > max)
max = points[a];
}
System.out.printf("Highest Name: %s Highest Points: %s", Names[5], max);
}
public static int findThatName(String[] Names, String name) {
int index = -1;
for (int a = 0; a < Names.length; a++) {
if (Names[a].equals(name)) {
index = a;
break;
}
}
return index;
}
}
Specifically, within the showBest method. Instead of using Names[5], am I able to get something like Names[i]? Or maybe how would I use the index of the max score to be the same index of Names?
edit: Sorry I had to change the wording of the code...
You can store both max value and its index.
int index = 0;
int max = scores[0];
for (int i = 1; i < scores.length; i++) {
if (scores[i] > max) {
index = i;
max = scores[i];
}
}
System.out.printf("Max Name: %s Max Score: %s", sNames[index], max);
we should do this in java way, or the Object Oriented way.
For that we will need a Student class.
public class Student implements Comparable<Student> {
private Integer score;
private String name;
public Student() {
super();
}
public Student(Integer score, String name) {
super();
this.score = score;
this.name = name;
}
public Integer getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public int compareTo(Student o) {
return this.score.compareTo(o.getScore());
}
#Override
public String toString() {
return "Student [score=" + score + ", name=" + name + "]";
}
}
Then we can use this Student class anywhere and play around with the list of students as we want, like below.
public class Driver {
public static void main(String[] args) {
Student s1 = new Student(67, "Billy");
Student s2 = new Student(86, "Bobbi");
Student s3 = new Student(90, "Barbara");
Student s4 = new Student(20, "Beni");
Student s5 = new Student(55, "Baron");
Student s6 = new Student(98, "Becky");
Student s7 = new Student(90, "Ben");
List<Student> students = new ArrayList<>();
students.add(s1);
students.add(s2);
students.add(s3);
students.add(s4);
students.add(s5);
students.add(s6);
students.add(s7);
System.out.println("Minimum score student is :");
System.out.println(getMinScoreSudent(students));
System.out.println("\nMaximum score student is :");
System.out.println(getMaxScoreSudent(students));
System.out.println("\nAll Sudents :");
printStudentsInConsole(students);
}
public static Student getMinScoreSudent(List<Student> students) {
Collections.sort(students, Comparator.comparing(Student::getScore));
return students.get(0);
}
public static Student getMaxScoreSudent(List<Student> students) {
Collections.sort(students, Comparator.comparing(Student::getScore).reversed());
return students.get(0);
}
public static void printStudentsInConsole(List<Student> students) {
Collections.sort(students, Comparator.comparing(Student::getScore));
students.stream().forEach(student -> System.out.println(student));
}
This prints below message in console.
Minimum score student is :
Student [score=20, name=Beni]
Maximum score student is :
Student [score=98, name=Becky]
All Sudents :
Student [score=20, name=Beni]
Student [score=55, name=Baron]
Student [score=67, name=Billy]
Student [score=86, name=Bobbi]
Student [score=90, name=Barbara]
Student [score=90, name=Ben]
Student [score=98, name=Becky]
When I run this code, for some reason when it hits test10 to be added into the Array sort, the addListing method ignores the for loop and just skips to the bottom. I am curious why the for loop runs for test2.addListing(test); and test2.addListing(test9); but not for the one after.
import java.util.Scanner;
public class TestListings {
public static void main(String[] args) {
StudentListings test = new StudentListings();
StudentListings test9 = new StudentListings();
StudentListings test10 = new StudentListings();
test.input();
test9.input();
test10.input();
Scanner sc = new Scanner(System.in);
int aSize = 0;
System.out.print("Enter Array Size: ");
aSize = Integer.parseInt(sc.nextLine());
ArraySort test2 = new ArraySort(aSize);
test2.addListing(test);
test2.addListing(test9);
test2.addListing(test10);
test2.showAllListings();
}
}
This is the method written, and it runs for the first run through, next = 0; intially, but the 3rd time (in test10) it just looks at the line and skips it.
public class ArraySort
{
private StudentListings[] data;
private int size = 0;
private int next = 0;
public ArraySort()
{
data = new StudentListings[size];
size = 0;
next = 0;
}
public ArraySort(int ArraySize)
{
size = ArraySize;
data = new StudentListings[size];
next = 0;
}
public void addListing(StudentListings newListing)
{
System.out.print(next);
for(i = next - 1; i <= 0; i--)
{
try {
if (newListing.compareTo(data[i].getLName()) < 0)
{
data[i+1] = data[i].deepCopy();
}
else
{
data[i+1] = newListing;
next++;
break;
}
}
catch(ArrayIndexOutOfBoundsException | NullPointerException exception)
{
int x = i + 1;
data[x] = newListing;
next++;
break;
}
}
System.out.print(next);
}
public void showAllListings()
{
for(int i = 0; i < next; i++)
{
System.out.println((i + 1) + ". " + data[i]);
}
}
}
This is the class that is getting created to be inserted into the array.
import java.util.Scanner;
public class StudentListings {
private String firstName;
private String lastName;
private int id;
private double gpa;
public StudentListings()
{
firstName = "";
lastName = "";
id = 0;
gpa = 0.0;
}
public StudentListings(String firstName, String lastName, int id,
double gpa)
{
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
this.gpa = gpa;
}
public void setName(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String getName()
{
return firstName + " " + lastName;
}
public void setId(int id)
{
this.id = id;
}
public int getId()
{
return id;
}
public void setGpa(double gpa)
{
this.gpa = gpa;
}
public double getGpa()
{
return gpa;
}
public String getLName()
{
return lastName;
}
public void input()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter First Name: ");
this.firstName = sc.nextLine();
System.out.print("Enter Last Name: ");
this.lastName = sc.nextLine();
System.out.print("Enter Student ID: ");
this.id = sc.nextInt();
System.out.print("Enter Student GPA: ");
this.gpa = Double.parseDouble(sc.next());
}
public String toString()
{
return "Last Name: " + lastName + " First Name: " + firstName + " ID:
" + id + " GPA: " + gpa;
}
public StudentListings deepCopy()
{
StudentListings clone = new StudentListings(firstName, lastName, id,
gpa);
return clone;
}
public int compareTo(String targetKey)
{
return(lastName.compareTo(targetKey));
}
}
If next is 0 the first time then it’s 2 the third time and i starts at 1 so the condition i <= 0 is false from the start
I'm not solving that problem, because in my opinion you're trying to do (intricately) something already defined in Java. When you create a class, and have to manage an array of object of that class, Java offers a very simple way to do that, I'll explain what I would do in your position step by step:
1 - The first thing to do is to define the comparison between the object belonging to that class, you can achieve that by overriding the method compareTo of that class (the class has to implement Comparable <YourObject>); in your case i guess it schould be something like:
public class StudentListings implements Comparable<StudentListings>{
...
#Override
public int compareTo(StudentListings element){
return ...;
}
}
In which you define when a StudentListing object is bigger than another.
2 - The second thing to do is to define an ArrayList<StudentListings> in your main, and initialize it:
ArrayList<StudentListings> yourArray = new ArrayList<>();
3 - Then you have to add the elements to that array (obviously after you initialized them):
yourArray.add(test);
yourArray.add(test9);
yourArray.add(test10);
4 - Now you have your array, not sorted, to sort it you just have to call the method
Collections.sort(yourArray);
Now you have your ArrayList of StudentListings sorted.
There is another way to achieve this result, that is described here, I don't like it very much because using that way you have to redefine the comparison everytime you need to sort an array and because your main code results more complex, but it has the same result of the steps I explained (therefore the linked method is useful if you have to sort two different arrays of the same class objects in different ways, eg. one by students name and the other by students surname).
I am trying to test my application by printing into an output.txt file. There is an input.txt file that already contains four honor students and at least two with the same GPA of 3.9, and three that are not honors students. The results should be sent to the output.txt file. The output.txt file should contain:
1) All of the students
2) The best student
3) Number of honors students in the list
4) Honors students
The input.txt file that I created contains the following (in order) last names, first names, id, GPA, and year.
The class TestStudents prints the input.txt file. However, I need it to utilize the input.txt file in order to print the above mentioned output.txt file. Thank you very much.
Student class -
public class Student
{
String lastName, firstName, id;
double gpa;
int year;
public Student (String lastName, String firstName, String id,
double gpa, int year)
{
this.lastName = lastName;
this.firstName = firstName;
this.id = id;
this.gpa = gpa;
this.year = year;
}
public String toString()
{
return this.lastName + ", " + this.firstName + ": " + this.id + " "
+ this.gpa + " " + this.year;
}
public double getGPA()
{
return gpa;
}
public boolean isBetter (Student s)
{
return (this.gpa > ((Student)s).getGPA());
}
public boolean isHonors()
{
if (this.gpa >= 3.5)
{
return true;
}
else
{
return false;
}
}
}
CS152 class -
import java.util.*;
import java.io.*;
public class CS152
{
public static final int MAXSIZE = 22;
private static int size = 0;
public static Student[] createList (Scanner scan) throws IOException
{
Student[] list = new Student [MAXSIZE];
return populateList (list, scan);
}
private static Student[] populateList (Student[] list, Scanner scan)
{
Student s;
if (size < MAXSIZE && scan.hasNext())
{
s = new Student (scan.next(), scan.next(), scan.next(),
scan.nextDouble(), scan.nextInt());
list[size] = s;
size++;
System.out.println (s);
return populateList (list, scan);
}
else
{
return list;
}
}
public static int getSize()
{
return size;
}
// Returns String of all students. Variable n is actual size of the list.
// Assume that n is positive. Recursive code.
public static String toString (Student[] list, int n)
{
String s = " ";
if (n == 1)
{
return s += list[0];
}
else
{
s += list[n].toString() + "\n";
s += "\n";
}
return s + toString (list, n - 1);
}
// Returns the best student. Must use method isBetter in the code.
// Variable n is actual size of the list. Assume that n is positive.
public static Student findBestStudent (Student[] list, int n)
{
if (n == 1)
{
return list[0];
}
else if (list[n].isBetter (list[n - 1]))
{
return list[n];
}
else
{
return findBestStudent (list, n - 1);
}
}
// Returns the number of honor students in the list.
// Must call the method isHonors(). Variable n is actual size of the list.
// Assume that n is positive.
public static int countHonors (Student[] list, int n)
{
if (n == 0)
{
return 0;
}
else if (list[n].isHonors())
{
return 1 + countHonors (list, n - 1);
}
else
{
return countHonors (list, n - 1);
}
}
static ArrayList<Student> studentsList = new ArrayList<Student>();
public static ArrayList <Student> honorsStuds (Student[] list, int n)
{
if (n == 0)
{
return studentsList;
}
else
{
boolean currentIsHonors = list[n - 1].isHonors();
if (currentIsHonors)
{
studentsList.add(list[n - 1]);
return honorsStuds (list, n - 1);
}
else
{
return honorsStuds (list, n - 1);
}
}
}
}
TestStudents class -
import java.io.*;
import java.util.*;
public class TestStudents
{
public static void main (String[] args) throws IOException
{
File input = new File ("input.txt");
Scanner scan = new Scanner (input);
Student[] studentArray = CS152.createList (scan);
}
}
I incorporated the FileWriter into the TestStudents class. A list of all students is now displayed. I am still having difficulties trying to call the methods findBestStudent, countHonors, and honorsStuds and implementing them into TestStudents. Here is the revised TestStudents class:
TestStudents class -
import java.io.*;
import java.util.*;
public class TestStudents
{
public static void main (String[] args) throws IOException
{
File input = new File ("input.txt");
Scanner scan = new Scanner (input);
System.out.println ("All students: ");
Student[] studentArray = CS152.createList (scan);
File output = new File ("output.txt");
FileWriter fWriter = new FileWriter (output);
PrintWriter pWriter = new PrintWriter (fWriter);
pWriter.println (input);
pWriter.close();
}
}
To write to a file, you need a FileWriter.
Using a FileWriter and Try-with-resources, usage would look something like this:
try(FileWriter w = new FileWriter(new File("output.txt"))) {
w.append("Some string");
} catch (IOException ex) {
Logger.getLogger(Output.class.getName()).log(Level.SEVERE, null, ex);
}
If you don't use a try-with-resources, make sure to close() the Writer to make sure resources do not leak. In fact, you should also make sure to close your Scanner as well, as leaving it un-closed will leak resources.
In the future, ask one question per post.
To access your Students, you just need to read them from the array.
System.out.println(studentArray[0].getGPA()); // prints the GPA of the first student
for (int i=0; i<CS152.getSize(); i++) {
System.out.println(studentArray[i]); // prints every Student
}
[[Note that this design of having a long array with null elements at the end with CS152.class telling you how many are filled is bad design. I would have the read procedure return a List<Student>, which manages its own length. Given the name of the class is CS152, however, this is probably either given to you by the teacher of CS-152 or done previously, so I'll work with what you have.]]
I am beginner in Java. I need help to proceed my code. Thanks in advance.
Question: Given a unsorted list of 5 athletes nominated for the coaching class, provide a way for the coach to search for the athlete name and provide grades. Finally print the list of athletes’ names with their grade in the sorted order of their names. Search for the athlete with highest grade.
package student;
import java.util.Scanner;
public class Atheletes {
String name;
static String grade,grade1,grade2,grade3,grade4;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the name of athelete1 and grade");
grade1 = in.nextLine();
Scanner ino = new Scanner(System.in);
System.out.println("Enter the name of athelete2 and grade");
grade2 = ino.nextLine();
Scanner ine = new Scanner(System.in);
System.out.println("Enter the name of athelete3and grade");
grade3 = ine.nextLine();
Scanner inp = new Scanner(System.in);
System.out.println("Enter the name of athelete4 and grade");
grade4 = inp.nextLine();
}
}
I have simplified your code and added comments as necessary.
// number of Athletes you want
Athlete[] eAthlete = new Athlete[5];
// Name of each athlete
String[] names = { "ss", "aa", "bb", "cc", "xx" };
// On each iteration, the name of the Athlete
// and his/her grade is set,
Scanner in = new Scanner(System.in);
for (int i = 0; i < eAthlete.length; i++) {
eAthlete[i] = new Athlete();
eAthlete[i].setName(names[i]);
System.out.println("Please enter Grade for: "
+ eAthlete[i].getName());
eAthlete[i].setGrade(in.nextLine());
}
in.close();
// Print all athletes with their grades,
System.out.println("Before Sorting");
for (Athlete s : eAthlete) {
System.out.println(s.getName() + " " + s.getGrade());
}
At this point, the grades and names are assigned to each athlete,
Output
Before Sorting
ss 123
aa 65465
bb 4654
cc .0231
xx 23123
Now we need to sort these Athletes based on their names.
We could have designed our own Comparator but since, you are not allowed to use Collections.sort, we would use rather poor approach i.e bubble sorting,
String tempStr;
for (int t=0; t<eAthlete.length-1; t++)
{
for (int i= 0; i < eAthlete.length - t -1; i++)
{
if(eAthlete[i+1].getName().compareTo(eAthlete[i].getName())<0)
{
tempStr = eAthlete[i].getName();
eAthlete[i].setName(eAthlete[i+1].getName());
eAthlete[i+1].setName(tempStr);
}
}
}
Printing the sorted athletes with their grades,
System.out.println("After Sorting");
for (Athelete s : eAthelete){
System.out.println(s.getName() + " " + s.getGrade());
}
Output:
After Sorting
aa 65465
bb 4654
cc .0231
ss 123
xx 23123
observe the names in above output.
here is your Athlete class,
class Athlete {
private String name;
private String grade;
public void setName(String name) {
this.name = name;
}
public void setGrade(String gr) {
grade = gr;
}
public String getGrade() {
return grade;
}
public String getName() {
return name;
}
}
Here is the complete code,
public class Main {
public static void main(String[] args) {
Athlete[] eAthlete = new Athlete[5];
String[] names = { "ss", "aa", "bb", "cc", "xx" };
Scanner in = new Scanner(System.in);
for (int i = 0; i < eAthlete.length; i++) {
eAthlete[i] = new Athlete();
eAthlete[i].setName(names[i]);
System.out.println("Please enter Grade for: "
+ eAthlete[i].getName());
eAthlete[i].setGrade(in.nextLine());
}
in.close();
// Print all athletes with their grades,
System.out.println("Before Sorting");
for (Athlete s : eAthlete) {
System.out.println(s.getName() + " " + s.getGrade());
}
String tempStr;
for (int t = 0; t < eAthlete.length - 1; t++) {
for (int i = 0; i < eAthlete.length - t - 1; i++) {
if (eAthlete[i + 1].getName().compareTo(eAthlete[i].getName()) < 0) {
tempStr = eAthlete[i].getName();
eAthlete[i].setName(eAthlete[i + 1].getName());
eAthlete[i + 1].setName(tempStr);
}
}
}
System.out.println("After Sorting");
for (Athlete s : eAthlete) {
System.out.println(s.getName() + " " + s.getGrade());
}
}
}
class Athlete {
private String name;
private String grade;
public void setName(String name) {
this.name = name;
}
public void setGrade(String gr) {
grade = gr;
}
public String getGrade() {
return grade;
}
public String getName() {
return name;
}
}
public class Athletes {
private String name;
private String grade;
public Athletes(String name, String grade) {
this.name = name;
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
#Override
public String toString() {
return "Athletes [name=" + name + ", grade=" + grade + "]";
}
public static void main(String[] args) {
List<Athletes> lijst = new ArrayList<Athletes>();
lijst.add(new Athletes("bbb", "Grade1"));
lijst.add(new Athletes("ccc", "Grade2"));
lijst.add(new Athletes("aaa", "Grade3"));
lijst.add(new Athletes("ddd", "Grade4"));
Collections.sort(lijst, new Comparator<Athletes>() {
#Override
public int compare(Athletes o1, Athletes o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (Athletes athletes : lijst) {
System.out.println(athletes);
}
}
}
You may write your own comparator Class to sort the Athelete on basis of their names
public class AtheleteComparator implements Comparator
{
#override
public int compare(Atheletes first,Atheletes second)
{
return first.name.compareTo(second.name);
}
}
Then simply use
Collections.sort(List<Athelete>list,Your own Comparator's object)
To find out athelete with highest grade write another comparator which compares grades
then use
Collections.sort(arrayList,Comparator); // Sort the arraylist
arrayList.get(arrayList.size() - 1); //gets the last item, largest for an ascending sort
Ok, since you can use arrays and for loops but not collections:
public class Sorter(){
private int[] grades = {7, 6, 4, 10, 8};
private String[] names = {"John", "Erik", "Bob", "Frank", "Judy"};
public static void main(String args[]) {
new Sorter();
}
public Sorter(){
int[] tempGrades = {0, 0, 0, 0, 0};
String[] tempNames = {"", "", "", "", ""};
for (int x = 0; x < tempGrades.length; x++) {
if (grades[x] < tempGrades[1]) {
tempGrades[0] = grades[x];
tempNames[0] = names[x];
} else if (grades[x] < tempGrades[2]) {
tempGrades[0] = tempGrades[1];
tempGrades[1] = grades[x];
tempNames[0] = tempNames[1];
tempNames[1] = names[x];
} else if (grades[x] < tempGrades[3]) {
tempGrades[0] = tempGrades[1];
tempGrades[1] = tempGrades[2];
tempGrades[2] = grades[x];
tempNames[0] = tempNames[1];
tempNames[1] = tempNames[2];
tempNames[2] = names[x];
} else if (grades[x] < tempGrades[4]) {
tempGrades[0] = tempGrades[1];
tempGrades[1] = tempGrades[2];
tempGrades[2] = tempGrades[3];
tempGrades[3] = grades[x];
tempNames[0] = tempNames[1];
tempNames[1] = tempNames[2];
tempNames[2] = tempNames[3];
tempNames[3] = names[x];
} else {
tempGrades[0] = tempGrades[1];
tempGrades[1] = tempGrades[2];
tempGrades[2] = tempGrades[3];
tempGrades[3] = tempGrades[4];
tempGrades[4] = grades[x];
tempNames[0] = tempNames[1];
tempNames[1] = tempNames[2];
tempNames[2] = tempNames[3];
tempNames[3] = tempNames[4];
tempNames[4] = names[x];
}
}
grades = tempGrades;
names = tempNames;
for (int x = 0; x < grades.length; x++) {
System.out.println(tempNames[x] + " " + tempGrades[x]);
}
}
}
just for the future:
you can use an ArrayList<Athlete> where Athlete is a class that accepts (String name, int grade) as constructor paramaters and sorts athletes by grade by implementing its own comparator or you can use a LinkedHashMap<Integer, String> that sorts values by Key<Integer>.
Note: Class names with plural like Athletes are best used for Singleton classes that only implement static methods and variables. Always name classes by function (in this case sorting), AthleteSorter is also viable.