pass an array of objects from one method to another in java

i want to pass an array of objects i have stored in one for loop to a second for loop in another method to display the contents. e.g:

public static Student[] add()
for(int i = 0; i < studentArray.length; i++)
        {
            System.out.print("Enter student name ");
            studentName = EasyIn.getString();
            System.out.print("Enter student Id ");
            studentId = EasyIn.getString();
            System.out.print("Enter mark ");
            studentMark = EasyIn.getInt();
            studentArray[i] = new Student(); //create object
            tempObject = new Student(studentName,studentId,studentMark);
            place = findPlace(studentArray,studentName, noOfElements);
            noOfElements = addOne(studentArray, place, tempObject, noOfElements);   
        }

into here

public static void displayAll()
{
Student[] anotherArray = add();
    for(int i = 0; i < anotherArray.length ; i++)
    {
        System.out.print(anotherArray[i].toString());
    }   
}

to call it in a menu here:

                        case '3': System.out.println("List All");
                                  displayAll();
                                  EasyIn.pause();

when i press 3 on the menu it just calls the add method again but when i add in the values into the array again then it displays the array. i just want to display the array only

Answer

change displayAll() to take the array as a parameter:

public void displayAll(Student[] students) {
  ...
}

and call it as follows:

Student [] students = add();

...

case '3': System.out.println("List All");
    displayAll(students);
    EasyIn.pause();

Leave a Reply

Your email address will not be published. Required fields are marked *