我成功添加了第一个学生,但是当我添加第二个学生时,线程“ ”
中出现异常:数组索引超出范围:11 main
java.lang.ArrayIndexOutOfBoundsException
at java.util.Vector.get(Unknown Source)
at business.StudentCollection.UseArray(StudentCollection.java:58
at business.Application.main(Application.java:30)
代码段
public class StudentCollection {
private Vector<Student> collection;
private int count;
public StudentCollection ()
{
collection=new Vector<Student>(10,2);
count=0;
for( int i=0;i< collection.capacity(); i++) //i read that object cannot be added to
vectors if empty
collection.add(i,new Student(0,"No Student",0));
}
public void addStud(int ID,String name,int Credits)
{
for(int i=0;i< collection.capacity();i++)
if(collection.get(i)==null) // new Error
collection.add(i,new Student(0,"No Student",0)); //making sure vector new index are filled
collection.add(count,new Student(ID,name,Credits));
count++;
}
public Student UseArray(int x){ \\ Error here line 58
return collection.get(x);
}
public int getlengthh(){
return collection.capacity();
}
}
public static void main (String [] args ){
StudentCollection C=new StudentCollection();
System.out.println("Enter Student's ID");
x=scan.nextInt();
for (int i=0;i< C.getlengthh();i++){
if(C.UseArray(i).getID()==x){ // Error here
System.out.println("A student with this ID already exists.Do you want to overwrite the existing student?yes/no");
scan.nextLine();
ans=scan.nextLine();
if (ans.equalsIgnoreCase("yes")){
C.delete(x);
continue;
}
else {
System.out.println("Enter Student's ID");
x=scan.nextInt();
}
}
}
System.out.println("Enter Student's name");
Str=scan.nextLine();
Str=scan.nextLine()+Str;
System.out.println("Enter number of credits");
y=scan.nextInt();
C.addStud(x,Str,y);
}