在java中将一个对象数组从一个方法传递给另一个方法

时间:2012-04-30 10:44:11

标签: java arrays object loops for-loop

我想将一个已存储在一个for循环中的对象数组传递给另一个for循环的另一个方法来显示内容。 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);   
        }

进入这里

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

在这里的菜单中调用它:

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

当我在菜单上按3时它再次调用add方法但是当我再次将值添加到数组中时它会显示数组。我只想显示数组

3 个答案:

答案 0 :(得分:1)

更改displayAll()以将数组作为参数:

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

并按如下方式调用:

Student [] students = add();

...

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

答案 1 :(得分:1)

您可以将displayAll方法定义更改为

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

然后在切换大小写之前调用add方法,并以student []作为参数调用displayAll方法。

答案 2 :(得分:0)

与其他人相似

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

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