2

最初の生徒を正常に追加していますが、2 番目の生徒を追加すると
、スレッド " 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) 

コードのセグメント

 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);

    }
4

2 に答える 2

1

に変更

 public Student UseArray(int x){  \\ Error here line 58
     if(collection.size() > x)
        return collection.get(x); 
     return null; 

    }

容量とサイズに違いがあります。VectorCapacity は、現在の要素と次の要素を保持するために作成された配列の長さを返します。size は、すでにベクターに入れられている要素の数です。そうは言っても、要素の存在を確認している間は、以下のように容量使用サイズを使用しません。

 public int getlengthh(){  
    return collection.size();  
                } 

capacityより大きい場合でもindex、追加すると例外がスローされる可能性があります。こちらをご覧ください

于 2013-01-13T12:45:51.830 に答える
0

のようなコレクション クラスの要点はVector、配列のように手動でインデックスを作成する必要がないことです。カウント変数も維持する必要はありません。何人の生徒がいるかを知りたい場合はsize()、Vector を呼び出すだけです。ここで、Vector のスレッド セーフが必要でない限り、代わりに ArrayList を使用しますが、どちらも List の実装であるため、必要なのは を呼び出すだけadd(Student)です。

続行する前に、 Java Collections Trailをよく見てください。

また、スタイル上の注意として、ソースのフォーマットをクリーンアップします。インデントに一貫性がないと、コードのバグを確認するのが非常に難しくなります。

于 2013-01-13T13:05:10.030 に答える