What's wrong with the searchStudent method that returns 0 every time? int searchStudent(String target)Finds and gives the desired index by name.
import java.util.ArrayList;
class Student {
String name;
double gpa;
public Student(String name, double gpa) {
this.name = name;
this.gpa = gpa;
}
public String getName() {
return name;
}
}
public class StackOverflow {
static ArrayList<Student> stu = new ArrayList<>();
public static void main(String[] args) {
stu.add(new Student("Hadi", 2.3)); // <-- every time shows 'Hadi'
stu.add(new Student("Jack", 1.8));
stu.add(new Student("Sara", 4.6));
System.out.println("----- Searching For A Student -----");
int recurse = searchStudent("Jack");
if (recurse == -1) {
System.out.println("There is no Student with this name !!");
} else { //if 'Jack' was in List show his name
System.out.println(getStudent(recurse).getName());
}
}
public static int searchStudent(String target) {
int indexTarget = -1;
for (Student z : stu) {
if (z.getName() != null && z.getName().contains(target)) {
indexTarget = z.getName().indexOf(target);
}
}
return indexTarget;
}
public static Student getStudent(int index) {
return stu.get(index);
}
}