我有一个代码,用于在数组列表中存储书籍数量,每次借书时,都会提示用户输入一个从 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");
}
}
慕容森
相关分类