我成功地添加了第一个学生,但当我添加第二个学生时,我会得到
线程"main“java.lang.ArrayIndexOutOfBoundsException中出现异常:数组索引超出范围: 11
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);
}发布于 2013-01-13 20:45:52
修改为
public Student UseArray(int x){ \\ Error here line 58
if(collection.size() > x)
return collection.get(x);
return null;
}容量和大小是有区别的。Capacity返回Vector为保存当前元素和传入元素而创建的数组的长度。而size是已经放入向量中的元素的数量。话虽如此,在检查元素是否存在时,请不要使用容量使用大小,如下所示:
public int getlengthh(){
return collection.size();
} 即使capacity比index大,add仍然会抛出异常。请参阅here
发布于 2013-01-13 21:05:10
像Vector这样的集合类的全部意义在于,您不需要像数组一样手动索引它们。您也不需要维护计数变量--当您想知道有多少学生时,只需在矢量上调用size()即可。现在,除非你需要向量的线程安全性,否则我会选择ArrayList,但它们都是List的实现,这意味着你所需要做的就是调用add(Student)。
在继续之前,我会好好看看Java Collections Trail。
此外,在风格上,清理您的源格式。不一致的缩进会让你很难检查代码中的bug。
https://stackoverflow.com/questions/14303568
复制相似问题