ArrayList不会显示其元素

时间:2019-03-21 07:29:08

标签: java arraylist

这是我的Object类:

public class Book {

   private String title;
   private int year;

   public Book(String title, int year){
      title = this.title;
      year = this.year;
   }

    public String getTitle(){return title;}
    public int getYear(){return year;}

    public String toString(){return (title + "\t" + year);}
}

应用程序类将从BookInput.txt中读取,该文件已经具有书名数据并在其中发布年份,并将数据传输到名为BookList的数组列表中。一个书名及其出版年份将记录在一个索引中(这意味着一个索引中有两个数据,即字符串和整数)

这是我的应用程序类:

    ArrayList <Book> BookList = new ArrayList();
    BufferedReader br = new BufferedReader (new FileReader ("bookInput.txt"));

    String str = br.readLine();
    while (str!=null){
        StringTokenizer st = new StringTokenizer(str,";");
        String title = st.nextToken();
        String yr = st.nextToken();
        int year = Integer.parseInt(yr);
        Book b1 = new Book (title,year);
        BookList.add(b1);
        str = br.readLine();
    }
    br.close();

    for (int i = 0; i < BookList.size(); i++){
        Book b2 = BookList.get(i);
        System.out.println("#" + (i+1) + " " + b2.getTitle() + " , " + b2.getYear());
    }

对于所有标题,我的显示将为空,对于所有发布年份,我的显示将为0。它可以编译而没有任何错误。

1 个答案:

答案 0 :(得分:3)

您必须反过来设置对象的属性,并且可以考虑将私有字段设置为final(在这种情况下,如果最终值在构造函数中未正确初始化,则会出现编译错误):

private final String title;
private final int year;

public Book(String title, int year){
   this.title = title;
   this.year = year;
}