Attempting a Binary Search on an Object Array [comparator] - java

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.`

Related

Attempting a Binary Search on a Object Array [comparator]

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;
}

Is there another way to get the index without using the index of the array? ex. Not using Array[5]

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]

The for loop in the method gets skipped when 3rd entry goes in. JAVA

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).

Comparing lines for a similar String in a text file

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);
}

Why can't I compare two Strings when using getters?

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;

Categories