我有一个代码,用于在数组列表中存储书籍数量,每次借书时,都会提示用户输入一个从 0 开始的数字,代表第一本书,1 代表第二本书,依此类推。它首先运行从数组列表中删除第一个对象,然后当它到达最后一个对象时,它抛出一个 IndexOutOfBoundException,这是我的代码块,请帮忙! //class doesn't do much than just gets the title of the book public class BookLibrary { String title; public BookLibrary(){}public void setTitle( String names) { title = names;}public String getTitle(){ return title;}}这是我从 arraylist 公共类 LibraryAssistant { 中删除对象的代码 ArrayList<BookLibrary> booklib = new ArrayList<>(); int numOfBooks = 0; public void setupLibrary(){ BookLibrary bc = new BookLibrary(); bc.setTitle("fantastic beasts and where to find them"); BookLibrary bc1 = new BookLibrary(); bc1.setTitle("Harry potter and the prisoner of azkabans"); BookLibrary bc2 = new BookLibrary(); bc2.setTitle("one day for the thief"); booklib.add(bc); booklib.add(bc1); booklib.add(bc2); numOfBooks++; for(BookLibrary book : booklib){ System.out.println(book.getTitle()); }}public void borrowbook(){ while(!booklib.isEmpty()){ String getbooknum = userInput("please enter a book number of the book you want to borrow"); int index = Integer.parseInt(getbooknum); if(index>=0){ booklib.remove(index); for(BookLibrary lb : booklib){ System.out.println(lb.getTitle()); } } numOfBooks--; } if(booklib.isEmpty()){ System.out.println("the library is empty"); }}
2 回答
慕容森
TA贡献1853条经验 获得超18个赞
IndexOutOfBoundException 背后的原因是每次删除对象时 arraylist 的大小都会减少。因此,如果您从书中删除第一个标题(索引 0),列表的大小将为 2。当用户进行第二次删除(索引 1)时,它会正常工作。但是当用户进行第三次删除(索引 2)时,它会抛出 IndexOutOfBoundException 因为 ArrayList 的大小现在是 1。
添加回答
举报
0/150
提交
取消