Reputation: 29
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
Upvotes: 0
Views: 9120
Reputation: 533472
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));
}
Upvotes: 2
Reputation: 2762
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.
Upvotes: 1
Reputation: 11638
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();
Upvotes: 1