使用.add(String)进行arrayList <book> </book>

时间:2014-04-24 18:20:51

标签: java arraylist

我正在开展一个学校项目,我需要从.txt文件中读取书籍编号和标题,并将它们放入一个数组列表中,这是迄今为止我所拥有的:

import java.io.*;
import java.awt.print.Book;
import java.util.*;


ArrayList <Book> Books = new ArrayList <Book> ();


public class Books{

String referenceNumber, title;

Books(String _referenceNumber, String _title){
    referenceNumber = _referenceNumber;
    title = _title;
   }
}

上面是必要的导入,数组和定义书籍组成的类。下面是它将从文件中读取文本并将其放入数组的方法,我的问题是我不知道用什么代替.add(字符串)(其中它说“Books.add(title) ;“因为它对我不起作用..

private void LoadActionPerformed(java.awt.event.ActionEvent evt) {
BufferedReader br = null;

try {
    br = new BufferedReader(new FileReader("BookList.txt"));
    String title;
    while ((title = br.readLine()) != null){
        Books.add(title);
    }
    } catch (IOException e){
} finally {
    try{
        br.close();
    } catch (IOException ex){
    }
}
String [] bookList = new String[Books.size()];
title.toArray(bookList);
}


Thanks for any help you can provide, I am a beginner to this and will appreciate any advice

2 个答案:

答案 0 :(得分:0)

尝试

...
String title = null;
String referenceNumber = null;
while ((title = br.readLine()) != null){
    referenceNumber = br.readLine();

    Books.add(new Book(referenceNumber,title));
}
...

您的文字文件看起来像

1
The Adventures of Tom Sawyer
2
Huckleberry Finn
4
The Sword in the Stone

- 编辑 -

更改课程声明

public class Book{

   String referenceNumber, title;

   public Book(String _referenceNumber, String _title){
        referenceNumber = _referenceNumber;
        title = _title;
   }
}

答案 1 :(得分:0)

ArrayList 图书的类型为 java.awt.print.Book ,它只能包含该类型的值。所以你不能在Arraylist中添加一个字符串。您必须将Arraylist的类型更改为String或将类型为Book的对象添加到Arraylist。