简体   繁体   中英

Print ArrayList from another Class

Evening everyone,

I am writing a code to allow students to search for internships. I have a class for Semesters, a class for Students(where student input is taken and stored into an ArrayList and the actual iSearch class. My code is basically doing everything I need it to do, except I have hit a brain block in trying to figure out the best way to output my ArrayList from the Student class out at the end of my program in the iSearch Class.

I am fairly new to Java, so if I haven't explained this correctly please let me know. I am trying to get the ArrayList's of student information to output at the end of the while loop in the iSearch Class.....so

To make this easy. Is it possible to print an Arraylist from another class.

A better way to solve this is to create a Student object for each student. In your current class the ArrayLists you are creating are deleted after every method call, since it is not referenced anymore.

Here is how I would do it:

Student Class:

public class Student {

    String firstName;
    String lastName;
    String interest;


    public Student(String firstName, String lastName, String interest) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.interest = interest;
    }
    public String getFirstName() {
        return firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public String getInterest() {
        return interest;
    }

}

In your iSearch class you create an ArrayList of students, which lets you add your students:

ArrayList<Student> students = new ArrayList<Student>();
    do {
        String firstName = input.next();
        String lastName = input.next();
        String interest = input.next();
        students.add(new Student(firstName, lastName, interest));
    } while (YOUR_CONDITION);

Then you can display each student by iterating through the ArrayList and accessing the getter and setter methods:

    students.foreach(student -> {
        System.out.println(student.getFirstName());
        System.out.println(student.getLastName());
        System.out.println(student.getInterest());
    });

Editing this a little will help you to solve your problem, but this is the basic solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM