Em gặp khó khăn một chút về việc thêm object vào arraylist mong mọi người giúp đỡ.
Em có một file books.txt có nội dung như sau, trong đó các số đầu(1,2,3) là id của từng quyển sách, sau đó tên và giá của từng quyển sách
1 Think big and Grow rich 10.95
2 The 7 habits of highly effective people 15.97
3 How to win friends and influence people 14.95
Ngoài ra, em có một object khác:
public class Book {
int id;
String name;
double price;
// attributes id, name, price
// constructor
public Book(int id, String name, double price) {
this.id =id;
this.name=name;
this.price =price;
}
public void setName(String name) {
this.name =name;
}
public void setPrice(double price) {
this.price =price;
}
/**
* return this as a String in the required format
*/
@Override
public String toString() {
return String.format("%-5s %-45s %-10s","id","Name","Price\n",id,name,price);
}
}
Yêu cầu là đưa dữ liệu lấy được từ tệp txt sau đó truyền vào object Book sau đó thêm vào array list. Bài làm của em như sau:
public class BookManager {
ArrayList<Book> books;
// attribute books
public BookManager() {
this.books =new ArrayList<Book>();
}
public ArrayList<Book> getBooks() {
return books;
}
/**
* update this.books by reading books from file books.txt
*/
public void loadFromFile() throws FileNotFoundException {
System.out.println("Loading books...");
Scanner sc = new Scanner(new File("books.txt"));
String s = "";
while (sc.hasNext()) {
s += sc.nextLine() + "\n";
}
String[] data = s.split("\n");
int []id = new int[data.length];
String[] name = new String[data.length];
double[] price = new double[data.length];
for (int i = 0; i < data.length; i++) {
int a = Integer.parseInt(data[i].substring(4,5));
String b = data[i].substring(6,45);
Double c = Double.valueOf(data[i].substring(51,61));
id[i]=a;
name[i]=b;
price[i]=c;
Book new_books = new Book(id[i],name[i],price[i]);
books.add(new_books);
}
Em lấy dữ liệu bằng cách in ra toàn bộ nội dung của file txt, sau đó tạo ra 3 array sẽ lưu từng giá trị tương ứng. Em đã lấy được các giá trị id, name và price của từng quyển sách rồi cho vào 3 array kia. Sau đó, em đã thử truyền dữ liệu vào object rồi thêm vào arraylist. Tuy nhiên, khi em test thứ như sau:
for(Book bk:books){
System.out.println(bk);
}
thì arraylist books chỉ có giá trị là id,name,price. Cho em hỏi là liệu bài làm của em đã đúng chưa ạ, hay do cách em test sai ạ, em mới học java mong được mọi người giúp đỡ. Xin chân thành cảm ơn.