I'm sorry if I used the wrong term, but I am only trying to print the name of a student from an ArrayList. The name can be found in quotes.
import java.util.ArrayList;
import java.util.Arrays;
public class Student {
private String name;
private int idNum;
public Student(String string, int i) {
name = string;
idNum = i;
}
public String getName()
{return name;}
public int getNum()
{return idNum;}
public String toString()
{return name+" "+idNum;}
public static void main(String[] args) {
ArrayList<Student> classroom = new ArrayList<Student>();
Student s1 = new Student("Eugene", 2596);
classroom.add(0, s1);
Student s2 = new Student("Bob", 1111);
classroom.add(1, s2);
Student s3 = new Student("Gary", 7993);
classroom.add(2, s3);
Student s4 = new Student("Dan", 6689);
classroom.add(3, s4);
Student s5 = new Student("Joe Kid", 3592);
classroom.set(2, s5);
Student s6 = new Student("Sue Kim", 8541);
classroom.set(3, s6);
classroom.remove(0);
Student s7 = new Student("Bob Lee", 6317);
classroom.add(s7);
classroom.remove(4);
System.out.println(classroom.toString());
for(int i=0; i<classroom.size(); i++){
System.out.println(classroom.**getName**(i));
}
}
}
There was an error at the end with getName(I put it in asterisks), and I'm not sure how to fix it. Thank you if you can find out how to fix it.
classroom.get(i).getName()- You need to get the object from theArrayListfirst, then you can access it's propertiesSystem.out.println(classroom.toString());can be written asSystem.out.println(classroom);: the method will automatically call thetoString()method for you (as well as handling the null case). You can also just writeclassroom.add(new Student("Eugene", 2596));, which means you don't have to keep making up new variable names.