Java adding items to a collection - java

I need to create a method call loadBooks. When called, this method create 5 books and adds them to the collection.
What i Have
public class Library
{
private ArrayList<Book> library;
public Library()
{
library = new ArrayList<>();
}
public void loadBooks()
{
library.add(new Book("T"));
library.add(new Book("A"));
library.add(new Book("C"))
library.add(new Book("O"));
library.add(new Book("S"));
}
Book Class:
class Book
{
private String author;
private String title;
private int numberOfPages;
private String refNumber;
private int borrowed;
private int total;
private boolean courseText;
public Book(String bookAuthor, String bookTitle, int numPages,boolean isCourseText)
{
author = bookAuthor;
title = bookTitle;
numberOfPages = numPages;
refNumber = "";
courseText = isCourseText;
}
I get a constructor Book in class Book cannot be applied to given types error then if i change it to something else it says cannot find class error.
Any ideas what to do or fix my code?

You're book class constructor accsepts 4 perameters, yet you're only passing it one in your loadBooks() method.
Just change your lines in loadBooks() to something like:
library.add(new Book("Author", "T", 1205 , true));

Related

Method to count the number of books of an author

So I need to create 3 classes "Book"(with fields author, title and body, as string), "Shelf"(with fields id (string) and books (array) and "Library". Then I shall create a method "countAuthor".which counts (and returns as an int) the number of books in the library written by an author whose name (String) is passed as an argument to the method:
class Book {
private String author;
public String getAuthor() {return author;}
private String title;
public String getTitle() {return title;}
private String body;
public String getBody() {return body;}
}
class Shelf {
private String id;
public String getId() {return id;}
private int[] books;
public int[] getBooks() {return books;}
}
class Library {
private int[] shelves;
public int[] getShelves() {return shelves;}
public int countAuthor(String authorName) { // returns the number of books in the library written by author whose name (String)
//is passed as an argument to the method.
int a = ;
return a; // a is the number of books of the author
}
}
After all, in the class (where the main method is stated), I need to add the necessary code and the program overall shall print the number of books an author has written. This is the class of the main method:
public class Exercise {
public static void main(String[] args) {
Shelf shelf1 = new Shelf("Shelf1",
new Book[] {
new Book("Babel", "Odessa Tales", "babelode"),
new Book("Joyce", "Ulisses", "joyceuli")
});
Shelf shelf2 = new Shelf("Shelf2",
new Book[] {
new Book("Mann", "Dr Faustus", "mannfau"),
new Book("Babel", "Red Cavalry", "babelred")
});
Library lib = new Library(
new Shelf[] { shelf1, shelf2 });
System.out.println("# of books by this author: " + lib.countAuthor("Babel"));
}
}
Which should print # of book by this author: 2
Where I am confused with is what to add to the countAuthor() method. And if I need anything in addition to the method. I am pretty new to Java so I still get confused with some structures, especially with the loops.
Here it is. In your code you are missing constructors that you are trying to use so I added them. The logic of counting the books is just go through all the shelves in the lib and count all the books on these shelves with the author name.
public class Exercise {
public static void main(String[] args) {
Shelf shelf1 = new Shelf("Shelf1", new Book[]{
new Book("Babel", "Odessa Tales", "babelode"),
new Book("Joyce", "Ulisses", "joyceuli")});
Shelf shelf2 = new Shelf("Shelf2",
new Book[]{
new Book("Mann", "Dr Faustus", "mannfau"),
new Book("Babel", "Red Cavalry", "babelred")
});
Library lib = new Library(new Shelf[]{shelf1, shelf2});
System.out.println("# of books by this author: " + lib.countAuthor("Babel"));
}
}
class Book {
public Book(String author, String title, String body) {
this.author = author;
this.title = title;
this.body = body;
}
private String author;
public String getAuthor() {
return author;
}
private String title;
public String getTitle() {
return title;
}
private String body;
public String getBody() {
return body;
}
}
class Shelf {
public Shelf(String id, Book[] books) {
this.id = id;
this.books = books;
}
private String id;
public String getId() {
return id;
}
private Book[] books;
public Book[] getBooks() {
return books;
}
}
class Library {
public Library(Shelf[] shelves) {
this.shelves = shelves;
}
private Shelf[] shelves;
public Shelf[] getShelves() {
return shelves;
}
public int countAuthor(
String authorName) { // returns the number of books in the library written by author whose name (String)
//is passed as an argument to the method.
int count = 0;
for (Shelf shelf : shelves) {
for (Book book : shelf.getBooks()) {
if (book.getAuthor().equals(authorName)) {
count++;
}
}
}
return count; // a is the number of books of the author
}
}
Output:
# of books by this author: 2
As I can see from your question, the structure will be like this.
Library can have many Shelf and in every Shelf there are many books.
So to count the no of books for a particular author, first you need all the books.
It will be something like this.
public int countAuthor(String author) {
int result = 0;
for(Shelf shelf : shelves) {
for(Book book : shelf.getBooks()) {
if(author.equals(book.getAuthor()) {
result++;
}
}
}
return result;
}

Array inside a Java Class?

public class Playlist
{
String title;
String genre;
Boolean privatePlaylist = true;
Song[] listOfSongs;
public Playlist(String tl, String gn, Boolean priv)
{
tl = title;
gn = genre;
priv = privatePlaylist;
}
Song[] mostPlayedSongs()
{
return listOfSongs;
}
}
Above is my code. I am trying to create a java class that returns a playlist. I want it to return a title, genre, whether the playlist is private or public. All three of these things are already constructed above. However, to that list, as a fourth property I would like to add an array that lists all the song in the playlist. The array is already a property I created above(Song[]listOfSongs). However, I do not know how to join this array to the other three properties and how to put the songs in this array. Any suggestions?
if you don't want to change the songs, you could just place it in the constructor:
public PlayList(String title, String genre, Boolean privatePlaylist, Song[] songs) {
this.title = title;
this.genre = genre;
this.privatePlaylist = privatePlaylist; //original constructor wasn't assigning this property
this.listOfSongs = listOfSongs;
}
if the list of songs shouldn't be added in the constructor (i.e, it needs to be updated) I would use an ArrayList so you can change the size:
// Field:
private ArrayList<Song> listOfSongs;
// Constructor
public PlayList(String title, String genre, Boolean privatePlaylist) {
this.title = title;
this.genre = genre;
this.privatePlaylist = privatePlaylist; //original constructor wasn't assigning this property
this.listOfSongs = new ArrayList<>();
}
// To edit the songs:
public void setListOfSongs (ArrayList<Song> listOfSongs) {
this.listOfSongs = listOfSongs;
}
import java.util.ArrayList;
public class Playlist {
public final String title;
public final String genre;
public final Boolean privatePlaylist;
public final ArrayList<Song> listOfSongs;
public Playlist(String tl, String gn, Boolean priv) {
title = tl;
genre = gn;
privatePlaylist = priv;
listOfSongs = new ArrayList<>();
}
}
Example usage:
public class Main {
public static void main(String[] args) {
Playlist pl = new Playlist("title", "genre", false);
pl.listOfSongs.add(...);
System.out.println(pl.title);
}
}

How to create a better object

Related to my previous thread, i want to print an output like this:
bookId = "1234" (String)
bookName = "Machine Learning" (String)
price = $20 (int)
ratings = (array of object)
rater = a, score = 5
rater = b, score = 3
But this time, i tried to use an OOP manner.
So first, i made a POJO class called ProductView, the class will be look like this:
public class ProductView {
// field
private String bookId;
private String bookName;
private int price;
private List<Ratings> ratings;
// a constructor i tried to make
public ProductView(String bookId, String bookName, int price, List<Ratings> ratings) {
this.bookId = bookId;
this.bookName = bookName;
this.price = price;
this.ratings = ratings;
}
public String getBookId() {
return bookId;
}
public void setBookId(String bookId) {
this.itemId = itemId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Ratings getRatings() {
return ratings;
}
public void setRatings(Ratings ratings) {
this.ratings = ratings;
}
}
After that, i made a class called Ratings with the following field:
public class Ratings {
private String rater;
private int score;
public Ratings(String rater, int score) {
this.rater = rater;
this.score = score;
}
}
And finally, i made a Main Class called Main:
public class Main {
public static void main(String[] args) {
}
}
In the Main Class, i want to create an instance of the ProductView class and give it some value.
But i don't know how to do it with a list object param in my constructor.
Anyone can give me some insight?
first:
List is an interface, you should pass an implementation of list such as ArrayList or similar
second:
you have a compilation error in ProductView -> SetBookId, in this.itemId you don't have itemId as member or constructor parameter
furthermore, in get/set rating you need to pass and return list of Ratings.
nameing:
Ratings is actually just a Rating, you can make a new class of List or just use the Rating as is but change the name
now for your Question:
you can initialize first the list with objects and then send it to the constructor
such as:
List<Ratings> ratings = new ArrayList<>();
ratings.add(new Ratings("rater",5));
ratings.add(new Ratings("rater2",6));
ProductView productView = new ProductView("bookId","bookName",1,ratings);
Or, just initialize the ArrayList in the Constructor, the first way is preferable:
ProductView productView1 = new ProductView("bookId","bookName",1,
new ArrayList<Ratings>(Arrays.asList(new Ratings("rater",5), new Ratings("rater2",6))
));
hopefully, this answers your question
same as DodgyCodeException mentioned in the comments.

How can I pass a parameter into a constructor of type of a class I have created?

For example:
I have created a Publisher class and I pass into a constructor.
public Book(String pulicationTitle, Date publicationDate, Publisher publisher, String ISBN_10, String ISBN_13, String authorName) {
super(pulicationTitle, publicationDate, publisher);
ISBN_10 = ISBN_10;
ISBN_13 = ISBN_13;
this.authorName = authorName;
bookCounter++;
}
And then in my testing class in which I excute:
Book book2 = new Book(pulicationTitle, publicationDate, publisher, ISBN_10, ISBN_13, authorName);
In my Publisher class there is a method called getPublisherId() and in my testing class I have to pass that id.
This what I did in my testing class:
Date date = new Date();
Publisher pub = new Publisher("Cenage Learning", "13344-Tobean Drive,Independence, KY 45536", "Josef Blumenfield");
Book book = new Book("The world is Flat", date,pub.getPublisherID(), "037889948837", "099887636627", "Thomas L. Friedman");
And it is giving me an error
My Publisher class:
import java.util.ArrayList;
public class Publisher {
static int publisherCounter;
protected static int publisherID;
protected static String publisherName;
private String publisherAddress;
private String contactName;
private ArrayList publications;
public Publisher(String publisherName, String publisherAddress,
String contactName) {
super();
this.publisherName = publisherName;
this.publisherAddress = publisherAddress;
this.contactName = contactName;
publisherCounter++;
publisherID = publisherCounter;
}
public static String getPublisherName() {
return publisherName;
}
public void setPublisherName(String publisherName) {
this.publisherName = publisherName;
}
public String getPublisherAddress() {
return publisherAddress;
}
public void setPublisherAddress(String publisherAddress) {
this.publisherAddress = publisherAddress;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String printPublisherDetails(){
return publisherID+publisherName+publisherAddress+contactName;
}
public String printAllPublications(){
return Publication.getPulicationTitle() + Journal.getArticleTitle();
}
public static int getPublisherID() {
return publisherID;
}
public ArrayList getPublications() {
return publications;
}
public void addPublication(String adds){
publications.add(adds);
}
}
Your Book constructor accepts an Publisher object and you are passing the publisher ID, either change your Book constructor or overload it :-
public Book(String pulicationTitle, Date publicationDate, int publisherId, String ISBN_10, String ISBN_13, String authorName) {
super(pulicationTitle, publicationDate, publisherId);
ISBN_10 = ISBN_10;
ISBN_13 = ISBN_13;
this.authorName = authorName;
bookCounter++;
}
Also change or overload publisher constructor since it accepts different parameters:-
public Publisher(String publicationTitle,Date publicationDate,int publicationId){
}
There are various problems in the code.The below modifications can solve some part of your code
Book class constructor is expecting Publisher object in your code but you are passing primitive type
Add the code below
You can have overloaded constructor
public Book(String pulicationTitle, Date publicationDate, String ISBN_10, String ISBN_13, String authorName) {
//operations
}
You can have a method in Book class like this pass the id expicitly using method call
public void getpubId(int pubId)
{
// use pubId
}
call the method from your testing class like this
//create book object
Book book = new Book("The world is Flat", date, "037889948837", "099887636627", "Thomas L. Friedman");
//instead of passing publisher id through constructor, pass it through a method call
book.getpubId(publisher.getId());

Calling methods in the main program

I am trying to access some information that my program isnt letting me.
in my method "addTrack" it doesnt recognise the myTracklist object. how do i call myTracklist.count by using a method in the main class?
public class CD {
String art;
String tit;
public CD(String artist, String title){
art = artist;
tit = title;
tracklist myTracklist = new tracklist(100);
}
public static void main(String[] args) {
String mainArtist;
String mainTitle;
CD myCD = new CD("Awesomeguy", "AwesomeCDName");
mainArtist = myCD.getArtist();
System.out.println(mainArtist);
mainTitle = myCD.getTitle();
System.out.println(mainTitle);
myCD.display();
}
public String getArtist(){
String person;
person = art;
return person;
}
public String getTitle(){
String name;
name = tit;
return name;
}
public boolean addTrack(String trackinfo){
boolean result = false;
if (myTracklist.count < 100){
myTracklist.add(trackinfo);
result = true;
}
return result;
}
public int numTracks(){
int amount;
amount = myTracklist.count();
return amount;
}
public void display(){
System.out.println("Artist = "+ art);
System.out.println("Title = "+ tit);
tracklist.display();
}
}
here is my tracklist class
public class tracklist {
int length;
int numUsed;
String[] storage;
public tracklist(int size){
length = size;
numUsed = 0;
storage = new String[length];
}
public int count(){
return numUsed;
}
}
You've got scope problems in that you're declaring tracklist inside the CD constructor so that it only exists inside of the constructor and nowhere else. You must make it a field that is declared in the class for it to be usable at all the methods of the class.
So instead of
public class CD {
String art;
String tit;
public CD(String artist, String title){
art = artist;
tit = title;
tracklist myTracklist = new tracklist(100);
}
do
public class CD {
private String art;
private String tit;
private tracklist myTracklist; // declared
public CD(String artist, String title){
art = artist;
tit = title;
myTracklist = new tracklist(100); // initialized
}
// getter and setter methods of course.
It's a subtle but important distinction.
As an aside: you'll want to learn Java naming conventions so that others can more readily understand your code and your questions. Class names begin with an upper case letter.
As a second aside: don't have outside classes directly manipulate class fields. Use private fields and public getters and setters to allow the class to have more control over just what can be seen and what can be done.
it should be myTracklist.count() here:
if (myTracklist.count < 100){
Also:
String tit; // oh I love this object name!
tracklist myTracklist;
public CD(String artist, String title){
art = artist;
tit = title;
myTracklist = new tracklist(100);
}
Since you have declared it in your customer the "myTracklist" variable will only be visible in your constructor. Hence "addTrack" doesnt recognise the myTracklist object.
Declare it globally,
public class CD {
String art;
String tit;
tracklist myTracklist;
And initialize in the constructor as below.
myTracklist = new tracklist(100);
Keep the declaration of myTrackList outside the constructor. Like this:-
String tit;
tracklist myTracklist;
public CD(String artist, String title){
art = artist;
tit = title;
myTracklist = new tracklist(100);
}

Categories

Resources