I’m doing a simple program using arraylist. But I’ve encountered an error.
After deleting an element in the arraylist, using this code:
delnum=scanz.nextLine();
intdelnum=Integer.parseInt(delnum);
nem.remove(intdelnum);
corz.remove(intdelnum);
skul.remove(intdelnum);
gen.remove(intdelnum);
I’m having problems with adding another record after a delete. From what I see, the index, where I’m storing the next element is greater than the size, since I deleted an item.
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);
I get this error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 3
Please help,
In your case You don’t need to maintain index while adding in ArrayList.
I think in your case you require it as you save students information in multipple ArrayList like name in nem arraylist, course in corz arraylist …etc. And then you use it for corelation. I think this is not very good design.
Good design would have been to create Student object with details like name, course, address etc, And then add Student object to Arraylist.
Then your code will change to:
Hope this is helpful.