public class Student { //student object class containing name and id
String name;
int ID;
public Student(String name, int ID) {
this.name = name;
this.ID = ID;
}
@Override
public String toString() {
return name +" "+ ID;
}
}
//another class with two array lists, an array of students in a class and an array of students waiting for help
ArrayList<Student> inClass = new ArrayList<Student>();
ArrayList<Integer> inLine = new ArrayList<Integer>(); //IDs of students who are waiting for help
public boolean addStudentInLine(Integer id) {
for(int i = 0; i<inClass.size(); i++) {
if (inClass.get(i).ID != id) {
return false;
}
if (inClass.get(i).ID == id) {
inClass.add(id);
}
}
}
For the addStudentInLine method, I need to add the id to the integer Arraylist inLine if the id exists in inClass arraylist.(only students in a class can receive help) If the id does not exist in inClass arrayList, return false. I'm not sure how to traverse through the inClass arrayList in order to see if the id already exist because inClass arrayList consists of student objects. I've tried .contain() method but it also seems to not work. can someone please help?
You should reverse the condition in addStudentInLine
method, If any Student
id matching to ID
add that ID
to inLine
list and return true
or else just return `false
public boolean addStudentInLine(Integer id) {
for(int i = 0; i<inClass.size(); i++) {
if (inClass.get(i).ID.equals(id)) {
inClass.add(id);
return true;
}
}
return false;
}
You can also use for-each
block
public boolean addStudentInLine(Integer id) {
for(Student stu : inClass) {
if (stu.ID.equals(id)) {
inClass.add(id);
return true;
}
}
return false;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments