2010-08-01 73 views
1

我正在使用arraylist做一個簡單的程序。但是我遇到了一個錯誤。 ArrayList中刪除元素,使用此代碼後:刪除arraylist中的元素的問題

delnum=scanz.nextLine(); 
intdelnum=Integer.parseInt(delnum); 

nem.remove(intdelnum); 
corz.remove(intdelnum); 
skul.remove(intdelnum); 
gen.remove(intdelnum); 

我在與後刪除添加另一個記錄的問題。從我看到的情況來看,索引,我要存儲下一個元素的索引大於大小,因爲我刪除了一個項目。

do { 
    System.out.println("Add Records"); 

    System.out.print("Name: "); 
    nem.add(ctr, scanz.nextLine()); 

    System.out.print("Course: "); 
    corz.add(ctr, scanz.nextLine()); 

    System.out.print("Gender: "); 
    gen.add(ctr, scanz.nextLine()); 

    System.out.print("School: "); 
    skul.add(ctr, scanz.nextLine()); 

    System.out.println("Another?\n1.Yes\n2.No"); 
    adds=scanz.nextLine(); 
    addagain=Integer.parseInt(adds); 

    ctr++; 
} while(addagain==1); 

我得到這個錯誤:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 3 

請幫幫忙,

回答

1

在你的情況下你不需要在添加ArrayList時維護索引。 我覺得你的情況下,你需要它,因爲你保存學生信息在multiperm ArrayList像nem arraylist中的名字,當然在corz arraylist ...等。然後你將它用於相關性。我覺得這不是很好的設計。

好的設計應該是創建具有名稱,課程,地址等細節的學生對象,然後將學生對象添加到Arraylist。

public class Student { 
    private String name; 
    private String course; 
    private String gender; 
    private String school; 

    public String getName() { 
     return name; 
    } 
    public void setName(String name) { 
     this.name = name; 
    } 
    public String getCourse() { 
     return course; 
    } 
    public void setCourse(String course) { 
     this.course = course; 
    } 
    public String getGender() { 
     return gender; 
    } 
    public void setGender(String gender) { 
     this.gender = gender; 
    } 
    public String getSchool() { 
     return school; 
    } 
    public void setSchool(String school) { 
     this.school = school; 
    } 

} 

那麼你的代碼將變爲:

do { 
     Student student = new Student(); 
     System.out.println("Add Records"); 

     System.out.print("Name: "); 
     student.setName(scanz.nextLine()); 

     System.out.print("Course: "); 
     student.setCourse(scanz.nextLine()); 

     System.out.print("Gender: "); 
     student.setGender(scanz.nextLine()); 

     System.out.print("School: "); 
     student.setSchool(scanz.nextLine()); 

     // Add student to students ArrayList 
     students.add(student); 

     System.out.println("Another?\n1.Yes\n2.No"); 
     adds = scanz.nextLine(); 
     addagain = Integer.parseInt(adds); 
    } while (addagain == 1); 

希望這是有幫助的。

2

你應該只使用add(object)而非add(index, object) - 那麼你不會有您在上面encoutered問題。

4

什麼

ctr--; 
上刪除

0

正如我看到你每次插入物品後Ctr都會增加。但刪除後不會減少。所以,下一次當你去添加一個項目到這些列表時,由ctr表示的索引在列表中不存在。這就是你得到IndexOutOfBoundException的原因。

通過使用ctr--刪除,正如「Duckman」所說,解決了您現有的問題。但是,「A會」簡化了代碼。由於Osccam的Razor建議我喜歡「Will A」的回答