0

我想以另一种方法将存储在一个 for 循环中的对象数组传递给第二个 for 循环以显示内容。例如:

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 方法,但是当我再次将值添加到数组中时,它会显示数组。我只想显示数组

4

3 回答 3

1

和其他人一样

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));
}
于 2012-04-30T11:24:28.277 回答
1

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

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

然后在 switch case 之前从要调用的任何位置调用 add 方法,并以 student[] 作为参数调用 displayAll 方法。

于 2012-04-30T10:49:33.257 回答
1

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

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

并按如下方式调用它:

Student [] students = add();

...

case '3': System.out.println("List All");
    displayAll(students);
    EasyIn.pause();
于 2012-04-30T10:47:52.227 回答