2017-09-13 100 views
1

我试图弄清楚当用户键入书籍ID号时,如何删除我的Arraylist中的特定行。但它似乎无法在我的Arraylist中的任何地方找到该ID号。如何使用用户输入删除ArrayList中的特定行

private void removeBook() 
    // Removes a certain book from the Book List. 
    { 
     Scanner IDS = setbookID(); 
     int idNum = IDS.nextInt(); 
     if(bookList.contains(idNum)){ //problem 
      bookList.remove("B"+Integer.valueOf(idNum)); 
     } 
    } 

private Scanner setbookID(){ 
    Scanner bookID = new Scanner(System.in); 
    System.out.println("Enter your book's ID number. "); 
    return bookID;} 

书目是通过一个文本文件中读取出来吧作为一个String的ArrayList。在我的文本文件中的行看起来是这样的:

B998 ; Aithiopika ; Heliodorus ; 1829 

然而,如果在“998”的用户类型它不会删除ArrayList的这条线。关于如何去做这件事的任何想法?迭代器会有所帮助吗?

编辑:这是我如何将书籍添加到ArrayList的第一位。

private ArrayList<Book> readBooks(String filename) { 
     ArrayList<Book> lines = new ArrayList<>(); 
     readTextFileB(filename, lines); 
     return lines; 
    } 

private void readTextFileB(String filename, ArrayList<Book> lines) 
    // Reads the books.txt file. 
    { 
     Scanner s = null; 
     File infile = new File(filename); 
     try{ 
      FileInputStream fis = new FileInputStream(infile); 
      s = new Scanner(fis); 
     } catch (FileNotFoundException e){ 
      e.printStackTrace(); 
     } 
     while(s.hasNextLine()) 
      lines.add(new Book(s.nextLine())); 
    } 
+0

这里有很多潜在的原因。你能展示你的ArrayList以及如何用书籍填充它吗?添加之前,您是否从ID中删除'B'?你把它作为'Integer'加入吗? – Zircon

+0

是否有可能出现过多次这个ID?正如javadoc所说:“public boolean remove(Object o) 如果存在,则从该列表中删除指定元素的第一个出现**,如果该列表不包含该元素,则不变。因此,您应该首先检查是否只有一个事件,并且如果在尝试删除它之前可以在列表中找到它。 – kazu

+0

[检查ArrayList 是否包含部分字符串](https://stackoverflow.com/questions/6428005/check-if-arrayliststring-contains-part-of-a-string)或https:// stackoverflow .com/questions/8192665/how-to-search-for-a-string-in-a-arraylist或者https://stackoverflow.com/questions/6645379/partially-match-strings-in-case-of-list -containsstring – Tom

回答

0

你必须与你的代码多个问题。不清楚你是否想要从列表中删除Book对象。如果是这样,那么你需要比较ID字段(用iterator)的书对象假设你的Book类是象下面这样:

class Book { 
    int id; 

    Book(int id) { 
     this.id = id; 
    } 
} 

如果上述情况没有场景那么你的列表是Book对象的列表,然后你怎么能通过字符串作为参数在删除方法bookList.remove("B"+Integer.valueOf(idNum)); 你应该在这里传递书籍对象或索引号。

相关问题