简体   繁体   中英

ArrayList wont display its elements

This is my Object class:

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);}
}

the application class will read from the BookInput.txt which already has data of book title and publish year in it and will transfer the data into an arraylist called BookList. one book title and its publish year will be record in one index (which mean there's two data in one index, a string and an int)

This is my application class:

    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());
    }

my display will come out as null for all of the title and 0 for all publish year. it can be compile without any error.

You have to set object's attributes the other way around and you can consider to make private fields as final (in this case you get a compilation error in case of final values are not properly initialized in the constructor):

private final String title;
private final int year;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM