I am successfully adding the first student but when i add a second one i get
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 11
at java.util.Vector.get(Unknown Source)
at business.StudentCollection.UseArray(StudentCollection.java:58
at business.Application.main(Application.java:30)
Segments of code
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);
}
Modify to
There is a difference between capacity and size. Capacity returns length of array created by
Vectorto hold the present and the incoming elements. While size is the number of elements already put into the vector. Having said that, While checking for existence of elements don’t use capacity use size as below:Even if
capacityis bigger thanindexstill add can throw exception. See here