简体   繁体   English

从另一个类打印ArrayList

[英]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. 我有一个学期的班级,一个学生的班级(将学生的输入内容并存储到ArrayList和实际的iSearch班级中。我的代码基本上可以完成我需要做的所有事情,除了我在尝试在iSearch类的程序结尾处,找出从Student类输出ArrayList的最佳方法。

I am fairly new to Java, so if I haven't explained this correctly please let me know. 我对Java相当陌生,所以如果我没有正确解释这一点,请告诉我。 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 我正在尝试获取学生信息的ArrayList,以便在iSearch类的while循环结束时输出。

To make this easy. 为了使这容易。 Is it possible to print an Arraylist from another class. 是否可以从另一个类打印Arraylist。

A better way to solve this is to create a Student object for each student. 解决此问题的更好方法是为每个学生创建一个Student对象。 In your current class the ArrayLists you are creating are deleted after every method call, since it is not referenced anymore. 在当前类中,您创建的ArrayList在每次方法调用后都会被删除,因为不再引用它。

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: 在您的iSearch类别中,您将创建一个学生的ArrayList,可让您添加学生:

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: 然后,您可以通过遍历ArrayList并访问getter和setter方法来显示每个学生:

    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. 稍微编辑一下可以帮助您解决问题,但这是基本的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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