我正在嘗試學習Java,並且非常努力地理解類。我有一個String類型的數組,我需要將它放入一個對象的數組列表中,然後使用來自另一個類的方法中的數組列表的getList和setters。下面是我的一些代碼:使用數組和列表的Java類
public class Store
{
public static void main(String[] args) {
Book book1 = new Book();
Book book2 = new Book();
Book book3 = new Book();
printAll();
}
public void printAll(){
for(String book : booksOnHand){
super.print()
}
}
}
public class Book extends Store
{
private String title;
private String author;
private int year;
int[] stock = new int[4];//how many books are on hand at each of 5 stores
String [] books = {"War and Peace, Leo Tolstoy, 1869, 12, 7, 3, 9",
"Little Women, Louisa May Alcott, 1868, 4, 5, 2, 8",
"To Kill A Mockingbird, Harper Lee, 1960, 21, 18, 13, 6",
};
ArrayList<Book> booksOnHand = new ArrayList<Book>();
public Book(String title, String author, int year, int [] stock)
{
this.title = title;
this.author = author;
this.year = year;
this.stock = stock;
}
public String getTitle()
{
return title;
}
public String getAuthor()
{
return author;
}
public String getYear()
{
return year;
}
public int[] getStock()
{
return stock;
}
public void setTitle(String title)
{
this.title = title;
}
public void setAuthor(String author)
{
this.author = author;
}
public void setYear(int year)
{
this.year = year;
}
public void setStock(int count1, int count2, int count3, int count4)
{
stock[0] = count1;
stock[1] = count2;
stock[2] = count3;
stock[3] = count4;
}
void print()
{
System.out.println("Title: " + getTitle() + "\tAuthor: " + getAuthor() + "\tYear: " + getYear() + "\tStock: " + Arrays.toString(getStock()));
}
}
我有,我試過太多的代碼,包括Collections.addAll(booksOnHand, books);
,但我不知道放在哪裏ArrayList和如何實例化它,所以我可以在我的其他班級中使用它。預先感謝所有願意幫助的人!
您已經閱讀來自編譯器的錯誤信息?他們告訴你什麼是錯的,在哪裏。你不應該忽視它們。另外,爲什麼地獄書擴展存儲?書不是商店。所以Book不應該擴展Store。爲什麼一本書包含其他書籍?爲什麼一本書有股票?嘗試建模現實:商店有書。一本書沒有書。 –