0

I have a Student class which has;

 private String name;
 private long idNumber;

and getters and setters for them.

I also have a StudentTest class which has three different methods, 1. to ask user for the size of the array and then to create an array of type Student, 2. to ask user to populate the array with names and ID numbers for as long as the array is, 3. to show the contents of the array.

The code I have so far is;

 import java.util.Scanner; 

 public class StudentTest { 

// Main method.
public static void main(String [] args) {

}

// Method that asks user for size of array.
public static Student[] createArray() {

System.out.println("Enter size of array:");
Scanner userInputEntry = new Scanner(System.in);
int inputLength = userInputEntry.nextInt();
Student students[] = new Student[inputLength];

return students; 

}

// Method that asks user to populate array.
public static void populateArray(Student [] array) {

    for(int i=0;i<array.length().i++) {
        array[i] = new Student();
        System.out.println("Enter student name: ");
        Scanner userInputEntry = new Scanner(System.in);
        array[i].setName(userInputEntry.next());
        System.out.println("Enter student ID number: ");
        array[i].setIDNumber(userInputEntry .nextLong());
    }

}

// Method that displays contents of array.
public static void displayArray(Student[] array) {

}

}

How do I print the contents of the array back out to the user?

Laura Berry
  • 89
  • 2
  • 12
  • possible duplicate of [What's the simplest way to print an array?](http://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-an-array) – makasprzak Nov 20 '14 at 14:06

3 Answers3

0

Override the toString method in Student class and then use https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#toString(java.lang.Object[])

Nadir
  • 1,369
  • 1
  • 15
  • 28
0

in class Student u can override toString():

@Override
public void toString(){
return "name: " + this.name;
}

and create a simple for loop

for(int i = 0; i < array.length; i++){
System.out.println(array[i].toString());
}

hope this helps a little

Dave
  • 66
  • 4
0

use this in you display function if you don't want to override the toString method

for (int i = 0; i < array.length; i++) {
        System.out.println("Student id : "+array[i].getIdNumber() + " Student name : " +array[i].getName());
    }
Gaurav
  • 76
  • 4