I am suppose to create a Book class with the instance fields of title and number of pages.
I am then suppose to complete 14 tasks. I won't list them all but it includes adding books, then replacing a book then adding more.
The Tasks:
1. Add (book 1 - 350 pages)
2.Add (book 2 - 72 pages)
3.Replace Book 2 with (book 3 - 220 pages)
4.Add (book 4 - 120pages)
5.Add (book 5 - 90 pages at index position 1)
6.Add (Book 6 - 120 pages)
7. Add (book 7 - 170 pages)
8. Add(Book 8 - 400 pages)
9. Output the title of the book at index position 3
10. Output the size of the ArrayList.
11. Remove all books that contain 120 pages.
12. Find total num of pages in remaining books in the ArrayList.
12. Output the total number of pages in the remaining books in the ArrayList.
14. Using and enhanced for loop, ouput the current books in the ArrayLIst.
EDIT: THANK YOU ALL SO MUCH! I have fixed, refined and almost finished my code. Only problem is the last part which I am suppose to use enhanced for loop to output the current books. I get weird numbers whenever I do. package Book;
import java.util.ArrayList;
public class Book {
private String title;
private int pages;
public static void main(String[] args) {
ArrayList<Book> booklib = new ArrayList<Book>();
booklib.add(new Book("Book 1", 350));
booklib.add(new Book("Book 2", 72));
booklib.set(1, new Book("Book3", 220));
booklib.add(new Book("Book 4", 120));
booklib.add(1, new Book("Book 5", 90));
booklib.add(new Book("Book 6", 120));
booklib.add(new Book("Book 7", 170));
booklib.add(new Book("Book 8", 400));
System.out.println(booklib.get(3).gettitle());
System.out.println(booklib.size());
for (int i = 0; i < booklib.size(); i++)
if (booklib.get(i).getpages() == 120)
booklib.remove(i);
int sum = 0;
for (int i = 0; i < booklib.size(); i++) {
sum = sum + booklib.get(i).getpages();
}
System.out.println(sum);
for (Book books : booklib)
System.out.println(books);
}
public Book(String n, int p) {
title = n;
pages = p;
}
public int getpages() {
return pages;
}
public String gettitle() {
return title;
}
}
Librarysince it's a collection of books.