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");
}
}
Related
I have an array and I want to assign values in group of 3s
Name, Id, Population, Name, Id, Population, Name, Id, Population etc.
Is there a way to do that?
This is what I have
while (scanner.hasNext()) { `
scanner.useDelimiter(",");`
list.add(scanner.nextLine());}`
for(int i=0; i<list.size(); i++){
String n = list.get(i);
System.out.println("Hopefully going thru " + n);} //for me to check
String ar =list.toString();
Object [] a = ar.split(",");// splitting the array for each string
for(int h=0;h<a.length;h+=3) { // for [0] += 3 is Name
for(int j=1;j<a.length; j+=3) { // for [1] += 3 is Id
for(int k=2; k<a.length;k+=3) { //for[2]+= is Population
String name = a[h].toString();
String id = a[j].toString();
String population = a[k].toString();
System.out.println("name is "+ name);// this is just to check correct values
System.out.println("id is "+ id);// this is just to check correct values
System.out.println("population is " +population);// this is just to check correct values
CityRow cityRow = new CityRow(name,id,population); //?? I want every set of [0][1][2] to create a new object`
I don‘t think that ar has the correct data and I don‘t understand why you don’t work with list directly, but assuming that ar has the correct data, it should be possible to use:
for(int = 0; i < ar.length ; ) {
var cityRow = new CityRow(
ar[i++],
ar[i++],
ar[i++]
);
// remember to add cityRow to an
// appropriate list
}
You use Scanner so no need to split an array. You can read each separate value one-by-one directly from it.
public class Main {
public static void main(String... args) {
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\n|,");
System.out.print("Total groups: ");
int total = scan.nextInt();
List<City> cities = readCities(scan, total);
printCities(cities);
}
private static List<City> readCities(Scanner scan, int total) {
List<City> cities = new ArrayList<>(total);
System.out.println("Enter each city on a new line. Each line should be: <id>,<name>,<population>");
for (int i = 0; i < total; i++) {
String id = scan.next();
String name = scan.next();
int population = scan.nextInt();
cities.add(new City(id, name, population));
}
return cities;
}
private static void printCities(List<City> cities) {
System.out.println();
System.out.format("There are total %d cities.\n", cities.size());
int i = 1;
for (City city : cities) {
System.out.format("City №%d: id=%s, name=%s, population=%d\n", i++, city.id, city.name, city.population);
}
}
static class City {
private final String id;
private final String name;
private final int population;
public City(String id, String name, int population) {
this.id = id;
this.name = name;
this.population = population;
}
}
}
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);
}
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;
}
}
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.
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.