I have a two classes, Student
containing some basic info, and Course
, containing some basic info and an ArrayList
of Student
objects. I want to dynamically (from user input) populate new instances of both classes. For example, user is prompted for course name, teacher and asked if they want to add students to the course. When done with the course and all the students' information, the loop goes back to asking to add another course.
What I do is, create a Course
object and then add students. I manage Student
objects by just creating them after collecting user unput with courseInstance.addStudent(new Student(name, age, phone))
. It all works well for one course, but how do I manage multiple Course object, dynamically created from input?
Here is a code example:
public static void main(String[] args) {
// TODO code application logic here
Course course = new Course();
Scanner in = new Scanner(System.in);
String ans;
String name;
String gender;
String phone;
int age;
System.out.print("Enter course name: ");
ans = in.nextLine();
course.setName(ans);
System.out.print("Enter teacher name: ");
ans = in.nextLine();
course.setTeacher(ans);
while (true) {
System.out.print("Add student (yes or exit): ");
ans = in.nextLine();
if (ans.equals("exit")) {
break;
}
System.out.print("Enter name: ");
name = in.nextLine();
System.out.print("Enter age: ");
age = in.nextInt();
in.nextLine();
System.out.print("Enter gender: ");
gender = in.nextLine();
System.out.print("Enter phone number: ");
phone = in.nextLine();
course.addStudent(new Student(age, name, phone, gender));
}
in.close();
System.out.print(course);
}
How about having a List of Course
objects, and asking (in your while(true)
loop) what course each student is registering to?
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다