I am very new to java and I am not sure what i need to use in order to accomplish my goal... or I am not sure how to search for it on google or on stackoverflow...
Suppose I have a class Student that has a method to get/set their name, and their major. I also have another class Major which I can create an instance and add students that belong to this major in an ArrayList.
I have a Scanner so that the student can input their details...
I would write it like this in my Student class with a main:
package exp;
import java.util.Scanner;
public class Student {
private String name, major;
private int id;
public Student(){
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setMajor(String major){
this.major = major;
}
public String getMajor(){
return major;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Student student1 = new Student();
System.out.println("Enter name: ");
student1.setName(scan.next());
System.out.println("Enter major: ");
student1.setMajor(scan.next());
Major major1 = new Major();
major1.addStudents(student1);
System.out.println("List of students in major1: ");
major1.getStudents();
}
}
in my Major class:
package exp;
import java.util.ArrayList;
public class Major {
private ArrayList<Student> students;
public Major(){
students = new ArrayList<Student>();
}
public void addStudents(Student insertStudent){
students.add(insertStudent);
}
public void getStudents(){
for(Student student: students){
System.out.println(student.getName());
}
}
}
I understand this works fine... the student fills in their details... but what if there are 1000 or unknown number of students?? how do we get to create new instances instead of manually creating in the main "Student student2 = new Student();" and so on...and also how do we get to add the instance of a Student into the instance of a Major that they belong to?
Thank you very much!