简体   繁体   中英

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. eg:

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

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();

You can change your displayAll method definition to

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

and then call add method from wherever you want to call before switch case and call displayAll method with student[] as parameter.

Similar to others

public void displayAll(Student... students) {    
    for(Student student:students)
        System.out.print(student+" "); // so there is space between the toString
    System.out.println();
}

or

public void displayAll(Student... students) {    
    System.out.println(Arrays.asList(students));
}

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