Java 向量IndexOutOfBoundsException
我正在成功添加第一个学生,但当我添加第二个学生时,我得到了Java 向量IndexOutOfBoundsException,java,exception,vector,Java,Exception,Vector,我正在成功添加第一个学生,但当我添加第二个学生时,我得到了 线程“main”java.lang.ArrayIndexOutOfBoundsException:数组索引超出范围:11 at java.util.Vector.get(Unknown Source) at business.StudentCollection.UseArray(StudentCollection.java:58 at business.Application.main(Application.j
线程“
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);
}
public class StudentCollection{
私人病媒收集;
私人整数计数;
公共学生收藏()
{
集合=新载体(10,2);
计数=0;
对于(int i=0;i
修改为
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();
}
即使
容量
大于索引
仍然可以添加抛出异常。请参见像Vector
这样的集合类的全部要点是,您不需要像数组一样手动索引它们。您也不需要维护计数变量——当您想知道有多少学生时,只需在向量上调用size()
。现在,除非您需要Vector的线程安全性,否则我将使用ArrayList,但它们都是List的实现,这意味着您只需调用add(Student)
在继续之前,我会仔细看一看
另外,在风格方面,清理源代码格式。缩进不一致会使您很难检查代码中的bug。请避免使用“紧急”这个小词,因为它会增加您被否决的机会(我删除了它)。如果是紧急情况,您至少应该正确设置代码格式,不要让其他人这样做…这是我第一次来这里,很抱歉,它给了我一个nullpointexception,因此我编写了return new Student(0,“No Student”,0),而不是return null。但是它给了我之前相同的例外,但是在不同的位置。但是我可以问你为什么if(collection.size()>x)中的if(collection.size()>x)实际上x意味着索引,就像for(int x=0;x