这里我试图将对象添加到向量中并从向量中获取元素。 for循环向量内部给出了所有3个对象的详细信息。 但我想把对象放在循环之外。但它只给出了第三个对象的细节。
static Vector<Student> vector = null;
static Student student= null;
public static void AskStudentDetails(){
Scanner input = new Scanner(System.in);
student = new Student();
vector = new Vector<Student>();
for(int i=0; i<MAX_STUDENT; i++){
System.out.print("Coursework 01 Marks : ");
student.setCoursework1(input.nextInt());
vector.addElement(student); //add object to the vector
Student mm = vector.elementAt(0);
System.out.println(mm.getCoursework1());
}
input.close();
student = vector.elementAt(1);//assign to the object student
System.out.println(student.getCoursework1()); // always print only the value of third object
}
Student.class public class Student实现了java.io.Serializable {
private int coursework1;
public int getCoursework1() {
return coursework1;
}
public void setCoursework1(int coursework1) {
this.coursework1 = coursework1;
}
}
答案 0 :(得分:2)
从当前位置移除student = new Student();
并将其放在for循环中。
for(int i=0; i<MAX_STUDENT; i++){
student = new Student(); // Added here
System.out.print("Coursework 01 Marks : ");
}
答案 1 :(得分:1)
您只创建了1个Student
对象,并继续将其添加到向量中。
向向量添加对象并不意味着您要实例化新对象。如果你查看你的代码,你只需要调用new Student()
一次,这意味着你有一个对象可以从向量的每个字段继续引用。
这一行
student.setCoursework1(input.nextInt());
继续为同一对象的coursework1
属性赋值。
答案 2 :(得分:1)
只创建了一个在循环外部的Student对象。因此,为了使其工作,您必须在每次循环运行时创建一个对象。
for(int i=0; i<you_length; i++){
student = new Student(); //this is what you have to add. every time a new object is created.
System.out.print("etc");
}