Asking user for array size and populating array | Java

4.3k Views Asked by At

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) {

}

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

}

}

I'm not sure as to how to tackle the second method of asking the user to populate the array, any help will be greatly appreciated :)

3

There are 3 best solutions below

0
On BEST ANSWER

This may help you

 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; 

    }

public static void populateArray(Student [] array) {
    for(int i=0;i<array.length().i++)
    {
       array[i]=new Student();
       System.out.println("Enter Name");
         Scanner userInputEntry = new Scanner(System.in);
       array[i].setName(userInputEntry .next());
       System.out.println("Enter Id");
       array[i].setIdNumber(userInputEntry .nextLong());
    }
}
0
On

The easiest solution is probably a loop, in which you ask the user for input and then store it in your array.

Something like:

for(int i = 0; i < students.length(); i++){
   [Ask for input and store it]
}
0
On

i suppose something like this:

 // Method that asks user to populate array.
    public static void populateArray(Student [] array) {
        for(int i = 0; i < array.lenght;i++) {
            array[i]=new Student(name, id); //put here student name/id
        }
    }