public class HighSchoolStudent {
private String firstname;
private String lastname;
private double gpa;
public HighSchoolStudent(String firstname, String lastname, double gpa) {
this.firstname = firstname;
this.lastname = lastname;
this.gpa = gpa;
}
public String getFirstName() {
return firstname;
}
public String getLastName() {
return lastname;
}
public double getGpa() {
return gpa;
}
public String toString() {
return (lastname + ", " + firstname);
}
}
import java.util.*;
public class StudentSearchSort {
public static void main(String[] args) {
HighSchoolStudent Mike = new HighSchoolStudent("Michael", "Jackson", 3.5);
HighSchoolStudent Roger = new HighSchoolStudent("Roger", "Federer", 3.9);
HighSchoolStudent Serena = new HighSchoolStudent("Serena", "Williams", 3.7);
HighSchoolStudent Kobe = new HighSchoolStudent("Kobe", "Bryant", 3.3);
HighSchoolStudent Stephen = new HighSchoolStudent("Stephen", "Curry", 4.0);
HighSchoolStudent Tiger = new HighSchoolStudent("Tiger", "Woods", 2.9);
HighSchoolStudent Kanye = new HighSchoolStudent("Kanye", "West", 1.5);
ArrayList<HighSchoolStudent> studentlist = new ArrayList<HighSchoolStudent>();
studentlist.add(Serena);
studentlist.add(Tiger);
studentlist.add(Mike);
studentlist.add(Kanye);
studentlist.add(Roger);
studentlist.add(Stephen);
studentlist.add(Kobe);
// for (int i = 0; i < studentlist.size(); i++) {
// System.out.println(studentlist.get(i));
// }
// System.out.println(highestGpa(studentlist));
}
public static String highestGpa(ArrayList<HighSchoolStudent> students) {
HighSchoolStudent smartest = null;
double highestgpa = 0.0;
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getGpa() > highestgpa) {
smartest = students.get(i);
highestgpa = students.get(i).getGpa();
}
}
return smartest.toString() + " GPA: " + smartest.getGpa();
}
public static void lastNameSort(ArrayList<HighSchoolStudent> students) {
HighSchoolStudent[] sortedlist = new HighSchoolStudent[students.size()];
for (int i = 0; i < students.size(); i++) {
for (int j = i; j < students.size(); j++) {
int num = 10;
if(num <= 0) {
sortedlist[i] = students.get(i);
sortedlist[i+1] = students.get(i+1);
}else {
sortedlist[i] = students.get(i+1);
sortedlist[i+1] = students.get(i);
}
}
}
}
public static String lastNameSearch(ArrayList<HighSchoolStudent> students, String lastname) {
for(HighSchoolStudent student : students ) {
if (lastname.equalsIgnoreCase(student.getLastName())) {
HighSchoolStudent temp = students.get(i);
return (i+1) + ": " + temp.toString();
}
}
return null;
}
}
updated. this is everything i have. i dont know what to do anymore. and now im just typing random stuff so it will let me edit these changes in. i keep on getting compiling errors that say error: cant find symbol and an arrow points to the period before .getLastName() , i have no clue how to fix it
There's 2 errors.
You made a typo. The parameter is named students, not student. You missed an 's'
students is an ArrayList, which doesn't have a getLastName() method. You need call getLastName() on a HighSchoolStudent object like so: students.get(i).getLastName()
This is what you have:
public static String lastNameSearch(ArrayList<HighSchoolStudent> students, String lastname) {
for (int i = 0; i < students.size(); i++) {
// if (lastname.equalsIgnoreCase(student.getLastName())) {
// ^ this is where your error is
// you missed an 's'...
// vvv replace above with this line vvv
if (lastname.equalsIgnoreCase(students.get(i).getLastName())) {
HighSchoolStudent temp = students.get(i);
return (i+1) + ": " + temp.toString();
}
}
return null;
}
use equalsIgnoreCase instead
if (lastname.equalsIgnoreCase(students.get(i).getLastName())) {
you are converting whole object to string instead of give full name.
String temp = students.get(i).getFirstName()+" " + students.get(i).getLastName();
return (i + 1) + ": " + temp;
public static String lastNameSearch(List<HighSchoolStudent> `students`, String lastname) {
for(HighSchoolStudent student:students) {
if (lastname.equals(student.getLastName())) {
HighSchoolStudent temp = student;
return (i+1) + ": " + temp.toString();
}
}
return null;
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.`
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 and the position/location of that student should print. The issue I'm having is that when I perform the binarySearch to find the location/position of the Student it always returns "-1" and not the element position of the student. Any help?
Student class
package binarySearch;
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;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getSSN() {
return SSN;
}
public String getBankAccount() {
return bankAccount;
}
//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 key) {
return SSN.compareTo(key.getSSN());
}
}
where i sort my array for the binarySearch
package binarySearch;
public class ObjectBubbleSorter {
public static void bubbleSort(Comparable[] array) {
int lastPos;
int index;
Comparable temp;
for(lastPos = array.length-1; lastPos >= 0; lastPos -= 1) {
for(index = 0; index <= lastPos - 1; index+=1) {
if(array[index].compareTo(array[index+1]) > 0) {
temp = array[index];
array[index] = array[index+1];
array[index+1] = temp;
}
}
}
}
}
and where i perform my binarySearch
package binarySearch;
public class ObjectBubbleSortTest {
public static int binarySearch(Student list[], Student key) {
int low = 0;
int high = list.length - 1;
int middle = (low + high + 1)/2;
int location = -1;
while((low <= high) && (location == -1)){
if (list[middle].equals(key)) { //location current middle
location = middle;
}
else if(list[middle].compareTo(key) < 0 ) { //middle too high
high = middle - 1;
}
else {
low = middle + 1;
}
middle = (low + high + 1)/2;
}
return location;
}
public static void main(String[]args) {
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");
//sorting array
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();
//creating student obj
Student student1 = new Student("Ryan", "Petrowvoksi", "4345123", "0120345");
int studentSSN = binarySearch(student, student1);
System.out.print(studentSSN);
System.out.print(student1.getFirstName() + " " + student1.getLastName() + " was found at position: " + studentSSN);
}
When i perform that binarySearch it always returns -1 and not the student element position
Change this line list[middle].compareTo(key) < 0 into list[middle].compareTo(key) > 0 inside the binarySearch while-loop.
It seems that your compareTo function is working contrary to how you would like.
By the way, let me suggest you to change your binarySearch into this, more readable one:
public static int binarySearch(Student list[], Student key) {
int low = 0;
int high = list.length - 1;
int middle;
int location = -1;
while (low <= high) {
middle = (low + high + 1) / 2;
int compare = list[middle].compareTo(key);
if (compare == 0) {
location = middle;
return location;
} else if (compare > 0) {
high = middle - 1;
} else {
low = middle + 1;
}
}
return location;
}
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);
}
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.
I am doing a project and instead of using an array, I figured an array list would be better. I know I need to declare the array list and its methods, but I am not too sure where to go from there. Any suggestions? Here's code...
public class Student {
private String name;
private int[] tests;
public Student() {
this("");
}
public Student(String nm) {
this(nm, 3);
}
public Student(String nm, int n) {
name = nm;
tests = new int[n];
for (int i = 0; i < tests.length; i++) {
tests[i] = 0;
}
}
public Student(String nm, int[] t) {
tests = new int[t.length];
}
public Student(Student s) {
this(s.name, s.tests);
}
public int getNumberOfTests() {
return tests.length;
}
public void setName(String nm) {
name = nm;
}
public String getName() {
return name;
}
public void setScore(int i, int score) {
tests[i - 1] = score;
}
public int getScore(int i) {
return tests[i - 1];
}
public int getAverage() {
int sum = 0;
for (int score : tests) {
sum += score;
}
return sum / tests.length;
}
public int getHighScore() {
int highScore = 0;
for (int score : tests) {
highScore = Math.max(highScore, score);
}
return highScore;
}
public String toString() {
String str = "Name: " + name + "\n";
for (int i = 0; i < tests.length; i++) {
str += "test " + (i + 1) + ": " + tests[i] + "\n";
}
str += "Average: " + getAverage();
return str;
}
public String validateData() {
if (name.equals("")) {
return "SORRY: name required";
}
for (int score : tests) {
if (score < 0 || score > 100) {
String str = "SORRY: must have " + 0 + " <= test score <= " + 100;
return str;
}
}
return null;
}
}
I figured an array list would be better
Maybe. Maybe not. It depends. Does it look like you would get a benefit in using one based on the ArrayList API?
If your "list" never changes size, and you don't need to find things in it, then an array is just as good.
I know I need to declare the array list and its methods, but I am not
too sure where to go from there
You need to create a reference to an instance of an ArrayList. That's as simple as
List<Integer> myList = new ArrayList<Integer>();
in your class declaration. You don't need to "declare its methods". When you have a reference to an object, you can invoke its methods.
To use an ArrayList, you just need to declare and instantiate it:
// <SomeObject> tells Java what kind of things go in the ArrayList
ArrayList<SomeObject> aDescriptiveNameHere = new ArrayList<SomeObject>();
// This is also valid, since an ArrayList is also a List
List<SomeObject> list = new ArrayList<SomeObject>();
Then you can add things with the add() method:
// Please don't name your list "list"
list.add(new Thing(1));
list.add(new Thing(2));
You can get something by index (like you would with someArray[index]) as:
list.get(index);
// For example
Thing t = list.get(5);
You probably also need the size().
See the JavaDocs for more info.
All of the operations you're using are mirrored in the ArrayList API. One thing that's worth noting is that you cannot declare an ArrayList of primitive types, but for each of the primitive types there exists an Object that is the boxed version of the primative.
The boxed version of int is Integer, so you have
ArrayList<Integer> myList = new ArrayList<Integer>();
From there, you need to look up the methods you would need to use in order to manipulate the array. For example, if you want to add the number 42 to the end of the array, you would say
myList.add(42);
The ArrayList API is located here.
I think it could be better to use the stl vector instead make your own arrays
I tried to change the array to arraylist.
Reply if this doesn't compile correctly.
import java.util.ArrayList;
public class Student {
private String name;
// private int[] tests;
private ArrayList<Integer> tests;
public Student() {
this("");
}
public Student(String nm) {
// this(nm, 3);
name = nm;
}
/*
* public Student(String nm, int n) { name = nm; tests = new int[n]; for
* (int i = 0; i < tests.length; i++) { tests[i] = 0; } }
*/
/*
* public Student(String nm, int[] t) { tests = new int[t.length]; }
*/
public Student(Student s) {
this(s.name, s.tests);
}
public Student(String name2, ArrayList<Integer> tests2) {
name = name2;
tests = tests2;
}
public int getNumberOfTests() {
return tests.size();
}
public void setName(String nm) {
name = nm;
}
public String getName() {
return name;
}
// public void setScore(int i, int score) {
// tests[i - 1] = score;
public void setScore(int score) {
tests.add(score);
}
public int getScore(int i) {
// return tests[i - 1];
return tests.get(i - 1);
}
public int getAverage() {
int sum = 0;
for (int score : tests) {
sum += score;
}
// return sum / tests.length;
return sum / tests.size();
}
public int getHighScore() {
int highScore = 0;
for (int score : tests) {
highScore = Math.max(highScore, score);
}
return highScore;
}
public String toString() {
String str = "Name: " + name + "\n";
for (int i = 0; i < tests.size(); i++) {
str += "test " + (i + 1) + ": " + tests.get(i) + "\n";
}
str += "Average: " + getAverage();
return str;
}
public String validateData() {
if (name.equals("")) {
return "SORRY: name required";
}
for (int score : tests) {
if (score < 0 || score > 100) {
String str = "SORRY: must have " + 0 + " <= test score <= "
+ 100;
return str;
}
}
return null;
}
public ArrayList<Integer> getTests() {
return tests;
}
public void setTests(ArrayList<Integer> tests) {
this.tests = tests;
}
}