I am trying to create a program that will read from a .txt file that is formatted as such:
Total number of students
Name
Score1
Score2
Score3
Name
Score1
etc
My current code is this:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.io.*;
public class Project5 {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Enter file name: ");
String filename = in.nextLine();
File filetest = new File(filename);
Scanner imp = new Scanner(filetest);
List<String> studentList = new ArrayList<String>();
List<Integer> studentScores = new ArrayList<Integer>();
String total = imp.nextLine();
int i = 0;
try {
while (imp.hasNext()) {
if (imp.hasNextInt()) {
studentScores.add(imp.nextInt());
} else {
studentList.add(imp.nextLine());
i++;
}
}
} finally {
System.out.println("Name\t\tScore1\t\tScore2\t\tScore3");
System.out.println("-------------------------------------------------------");
System.out.println(total);
System.out.println(studentList.get(0) + "\t" + studentScores.subList(0, 3));
System.out.println(studentList.get(2) + studentScores.subList(3, 6));
System.out.println(studentList.get(4) + studentScores.subList(6, 9));
System.out.println(studentList.get(6) + studentScores.subList(9, 12));
imp.close();
in.close();
}
}
}
The format I want to display into the console is to list the name, then the three scores that student received, and to repeat it, but right now it is hard-coded just for the amount of students that are currently there, and I need it to be able to create output regardless of how many students there are.
Current output:
Total
Name [score1 score2 score3]
etc
Desired output:
Total
Name score1 score2 score3 (rather than with the [] )
etc
Any help is greatly appreciated.
More structural way to do this :
public class Project5 {
static class Student {
private String name;
private final List<Integer> scores;
private int total;
public Student() {
scores = new ArrayList<>();
total = 0;
}
public void setName(String name) {
this.name = name;
}
public void addScore(int score) {
scores.add(score);
total += score;
}
public String getName() {
return name;
}
public List<Integer> getScores() {
return scores;
}
public int getTotal() {
return total;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder(name).append('\t').append(total);
for (Integer score : scores) {
sb.append('\t').append(score);
}
return sb.toString();
}
}
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
System.out.println("Enter file name: ");
String filename = in.nextLine();
in.close();
File filetest = new File(filename);
Scanner imp = new Scanner(filetest);
int total = Integer.parseInt(imp.nextLine());
System.out.println("Name\tTotal\tScore 1\tScore 2\tScore 3");
for (int i = 0; i < total && imp.hasNextLine(); i++) {
Student student = new Student();
student.setName(imp.nextLine());
while (imp.hasNextInt()) {
student.addScore(imp.nextInt());
}
if (imp.hasNext()) {
imp.nextLine();
}
System.out.println(student);
}
imp.close();
}
}
The toString method of a List will return it in that format. If you want a different format, you can do this with a Stream:
System.out.println(studentList.get(2) + studentScores.subList(3, 6).stream().collect(Collectors.joining(" ");
Health warning: if this is for a school assignment where the use of Streams may get you accused of plagiarism, you will need to concatenate the elements yourself the long way.
This is the efficient solution that uses a StringBuilder and no Lists. A StringBuilder is basically a class that helps you to build string. Pretty straightforward.
// 1024 means that the initial capacity of sb is 1024
StringBuilder sb = new StringBuilder(1024);
try {
while (imp.hasNext()) {
if (imp.hasNextInt()) {
// add the scores and "tab" character to the string
sb.append("\t").append(imp.nextInt());
} else {
// add the name to the string
sb.append("\n").append(imp.nextLine());
i++; // btw.. why are you doing this i++ ??
}
}
} finally {
System.out.println("Name\t\tScore1\t\tScore2\t\tScore3");
System.out.println("-------------------------------------------------------");
System.out.println(total);
System.out.println(sb.toString());
imp.close();
in.close();
}
If you do want to use an arraylist then I suggest iterate through the arraylist like an array and print out the scores.
Related
Hello I am solving this problem given to me where I have to find average salary of a person which has least index id
import java.util.*;
import java.io.*;
public class Main {
public static int processData(ArrayList<String> array) {
for (String elem :array){
System.out.println(elem);
}
return 0;
}
public static void main (String[] args) {
ArrayList<String> inputData = new ArrayList<String>();
try {
Scanner in = new Scanner(new BufferedReader(new FileReader("input.txt")));
while(in.hasNextLine()) {
String line = in.nextLine().trim();
if (!line.isEmpty()) // Ignore blank lines
inputData.add(line);
}
int retVal = processData(inputData);
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
output.println("" + retVal);
output.close();
} catch (IOException e) {
System.out.println("IO error in input.txt or output.txt");
}
}
}
the program is accepting input from text file as follows
282, ij, 11, 1600000
273, cbg, 12, 800000
567, nj, 11, 800000
539, cb, 11, 600000
So the output will be
11 520000
I am able to print the elements from array list but not been able to access particular elements. Can anyone help me to access particular element which is, in this case, 11,160000 and so on?
Thank you in advance
Hint
You can calculate the AVG of the index 11 like this :
public static int processData(ArrayList<String> array) {
String[] spl;
int avg = 0, nbr = 0;
for (String elem : array) {
//split your String with ", " and space
spl = elem.split(", ");
//the index exist in the 3ed position, so you have to check your index if 11 then you can get its value
if(spl[2].equals("11")){
avg+=Integer.parseInt(spl[3]);
nbr++;
}
System.out.println(elem);
}
System.out.println((avg/nbr));
return avg / nbr;
}
When you print in your code you have to use :
output.println("11 " + retVal);
Hope this can gives you an idea.
You create a List of String to store employee data that contains multiple fields.
You should not as it mixes data employees.
The general idea I propose you :
1) Instead of storing all information in a List of String, use a List of Employee.
replace
ArrayList<String> inputData = new ArrayList<String>();
by
List<Employee> employees = new ArrayList<Employee>();
2)Use each read line that represents a person to create a instance of a custom Object, for example Employee.
So replace
inputData.add(line);
by something like that
String[] token = line.split(",");
Employee employee= new Employee(Integer.valueOf(token[0]),token[1],Integer.valueOf(token[2]),Integer.valueOftoken[3]));
employees.add(employee);
3) During this iteration to read the file, you can store in a variable that is the Employee with the minimum id.
4) After reading the file, you know the Employee with the minimum id. So you can iterate on the List of Employee and sum the salaries of the Employee that has this id and count the number of salary for this Employee.
When the loop is finished compute the avg : float avg = sum / (float)count;
It is not the most optimized way but it makes the job.
The following code will do what you need.
public class MyMain {
private static String inputFilePath = "/path/to/input.txt";
private static String outputFilePath = "/path/to/output.txt";
public static int processData(ArrayList<MyData> array) {
if (array.size() > 0) {
int minId = array.get(0).getData3();
for (MyData elem : array) {
if(elem.getData3() < minId) {
minId = elem.getData3();
}
}
int count = 0;
int total = 0;
for (MyData myData : array) {
if(myData.getData3() == minId) {
count++;
total += myData.getData4();
}
}
System.out.println("Min ID : " + minId + " -- Avg Sal : " + total/count);
}
return 0;
}
public static void main(String[] args) {
ArrayList<MyData> inputData = new ArrayList<>();
try {
Scanner in = new Scanner(new BufferedReader(new FileReader(inputFilePath)));
while (in.hasNextLine()) {
String line = in.nextLine().trim();
if (!line.isEmpty()) // Ignore blank lines
inputData.add(new MyData(line));
}
int retVal = processData(inputData);
PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter(outputFilePath)));
output.println("" + retVal);
output.close();
} catch (IOException e) {
System.out.println("IO error in input.txt or output.txt");
}
}
}
class MyData {
int data1;
String data2;
int data3;
int data4;
public MyData() {
// TODO Auto-generated constructor stub
}
public MyData(String data) {
String dataArr[] = data.split(",");
this.data1 = Integer.parseInt(dataArr[0].trim());
this.data2 = dataArr[1].trim();
this.data3 = Integer.parseInt(dataArr[2].trim());
this.data4 = Integer.parseInt(dataArr[3].trim());
}
public int getData1() {
return data1;
}
public void setData1(int data1) {
this.data1 = data1;
}
public String getData2() {
return data2;
}
public void setData2(String data2) {
this.data2 = data2;
}
public int getData3() {
return data3;
}
public void setData3(int data3) {
this.data3 = data3;
}
public int getData4() {
return data4;
}
public void setData4(int data4) {
this.data4 = data4;
}
}
After reading a text file and printing it out like so:
public static void main(String[] args) {
File file = new File("/Users/Len/Desktop/TextReader/src/example.txt");
ArrayList<String[]> arrayOfPeople = new ArrayList<>();
try {
Scanner input = new Scanner(file);
while (input.hasNext()) {
String num = input.nextLine();
System.out.println(num);
}
} catch (FileNotFoundException e) {
System.err.format("File Does Not Exist\n");
}
}
Print:
First Name, Surname, Age, Weight, Height
First Name, Surname, Age, Weight, Height
With this data, how do I calculate:
Oldest Person
Youngest Person
And print it out programmatically.
New to Java.
As user Bradimus mentioned in the comments, this is perfect for using classes.
If you look at the data in your file they are all the "same" type - every line has a first name, surname, age, weight and height. You can bundle them into an object and make them easier to use in your code.
Example:
public class Person {
public String firstName;
public String surname;
public int age;
public int height;
public int weight;
public Person(String input) {
//You can parse the input here. One 'input' is for example "Gordon, Byron, 37, 82, 178"
String[] splitString = input.split(", ");
this.firstName = splitString[0];
this.surname = splitString[1];
this.age = Integer.parseInt(splitString[2]);
this.height = Integer.parseInt(splitString[3]);
this.weight = Integer.parseInt(splitString[4]);
}
}
Then in your main class, you can just add them to an list like so. I added an example for how to calculate the oldest person, you can copy this logic (iterate over all the persons in the personList, perform check, return desired result) for the other tasks.
// Other code
public static void main(String[] args) {
List<People> peopleList = new ArrayList<>();
File file = new File("/Users/Len/Desktop/TextReader/src/example.txt");
try {
Scanner input = new Scanner(file);
while (input.hasNext()) {
String num = input.nextLine();
System.out.println(num);
peopleList.add(new Person(num));
} catch (FileNotFoundException e) {
System.err.format("File Does Not Exist\n");
}
Person oldestPerson = getOldestPerson(peopleList);
System.out.println("Oldest person: " + oldestPerson.firstName + " " + oldestPerson.surname);
}
public static Person getOldestPerson(List<Person> people) {
Person oldestPerson = null;
for (Person person: people) {
if (oldestPerson == null || person.age > oldestPerson.age) {
oldestPerson = person;
}
}
return oldestPerson;
}
You have an ArrayList called "arrayOfPeople", which you do not use yet. While reading your file line by line store the data in your list "arrayOfPeople" and calculate the needed values.
public static void main(String[] args) {
File file = new File("c:/Users/manna/desktop/example.txt");
ArrayList<String[]> arrayOfPeople = new ArrayList<>();
try {
Scanner input = new Scanner(file);
input.nextLine(); //do this to skip the first line (header)
while (input.hasNext()) {
String num = input.nextLine();
String[] personData = num.split(","); //returns the array of strings computed by splitting this string around matches of the given delimiter
arrayOfPeople.add(personData);
}
int oldest = Integer.parseInt(arrayOfPeople.get(0)[2].trim()); //Integer.parseInt("someString") parses the string argument as a signed decimal integer.
int youngest = Integer.parseInt(arrayOfPeople.get(0)[2].trim()); //String.trim() returns a copy of the string, with leading and trailing whitespace omitted
double totalWeight = 0;
double totalHeight = 0;
double totalAge = 0;
for(int i = 0; i< arrayOfPeople.size(); i++){
String[] personData = arrayOfPeople.get(i);
if(Integer.parseInt(personData[2].trim())>oldest){
oldest = Integer.parseInt(personData[2].trim());
}
if(Integer.parseInt(personData[2].trim())< youngest){
youngest = Integer.parseInt(personData[2].trim());
}
totalWeight = totalWeight + Double.parseDouble(personData[3].trim());
totalHeight = totalHeight + Double.parseDouble(personData[4].trim());
totalAge = totalAge + Double.parseDouble(personData[2].trim());
}
System.out.println("Oldest Person: " + oldest);
System.out.println("Youngest Person: " + youngest);
System.out.println("Average Weight: " + totalWeight/arrayOfPeople.size());
System.out.println("Average Height: " + totalHeight/arrayOfPeople.size());
System.out.println("Average Age: " + totalAge/arrayOfPeople.size());
} catch (FileNotFoundException e) {
System.err.format("File Does Not Exist\n");
}
}
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 in desperate need of more help this week. My professor is sub par and makes no effort to clear things up.
The Problem:
import a file and search for a specific piece of data that is requested by a user.
The output must return something similar to:
Sequential found ID number 77470, and its price is $49.55.
or
Sequential did not find ID number 77777.
I have no idea where to go from here, or even if this is correct....
public class MainClass
{
public static void main(String[] args)
{
Payroll acmePay = new Payroll();
Scanner myScanner = new Scanner(System.in);
int target;
acmePay.loadEmpNums();
System.out.println("Enter the product number you would like to search: ");
target = myScanner.nextInt();
System.out.print(acmePay.seqSearch(target));
myScanner.close();
}//END main
}//END class MainClass
Payroll Class:
public class Payroll
{
private int[] empNums = new int[1000];
private int empCount = 0;
Payroll(){} //Currently nothing done in constructor
public void loadEmpNums()
{
String name;
double salary;
empCount = 0; //Just to make sure!
try
{
String filename = "employees.dat";
Scanner infile = new Scanner (new FileInputStream(filename));
while (infile.hasNext())
{
//Read a complete record
empNums[empCount] = infile.nextInt();
name = infile.nextLine();
salary = infile.nextDouble();
//Increment the count of elements
++empCount;
}
infile.close();
}
catch (IOException ex)
{
//If file has problems, set the count to -1
empCount = -1;
ex.printStackTrace();
}
}//END loadEmpNums
public int seqSearch (int target)
{
int ind = 0;
int found = -1;
while (ind < empCount) {
if(target==empNums[ind])
{
found = ind;
ind = empCount;
}
else
{
++ind;
}
}
return found;
}
}//END class Payroll
Are you reading in from a txt file or are they entering the data in when you run the program?
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.