1

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.

2
  • 2
    classroom.get(i).getName() - You need to get the object from the ArrayList first, then you can access it's properties Commented Jan 10, 2016 at 23:07
  • Nit: System.out.println(classroom.toString()); can be written as System.out.println(classroom);: the method will automatically call the toString() method for you (as well as handling the null case). You can also just write classroom.add(new Student("Eugene", 2596));, which means you don't have to keep making up new variable names. Commented Jan 10, 2016 at 23:11

2 Answers 2

2

You could do

for (Student student: classroom) {
    System.out.println(student.getName());
}
Sign up to request clarification or add additional context in comments.

Comments

1

Use this:

System.out.println(classroom.get(i).getName());

You need to access the Student object first using classroom.get(i), then access his name.

Small P.S: if you're using Java 8, you can do this:

classroom.stream()
         .forEach(student -> System.out.println(student.getName()));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.