Creating a Book class, below are what the methods do. I'm currently stuck on how to add methods regarding removing author by name and email. I can't upload the UML image as I'm new and dont have enough rep points.
Create a new instance of the authors ArrayList inside the constructors.
Implement a method addAuthor(Author author) to add the given Author instance to this Book.
Implement a public method removeAuthorByName(String name) that uses the given String to search the authors ArrayList. If it finds an Author object with a name matching the given String it passes the reference to this object to a private method removeAuthor(Author author).
Implement a public method removeAuthorByEmail(String email) that uses the given String to search the authors ArrayList. If it finds an Author object with an email matching the given String it passes the reference to this object to a private method removeAuthor(Author author).
Implement a private method removeAuthor(Author author) which when given a reference to an Author object removes the reference to that object from the authors ArrayList.
The toString() method shall return "book-name by n authors", where n is the number of authors.
The printAuthors() method shall print the names of all the authors from an Arraylist.
My code :
class Book {
private String name;
private double price;
// private Author[] authors = new Author[5];
//priavte authors =new ArrayList<Author>();
private Map authors = new HashMap<String, Author>();
// private ArrayList<Author> authors = new ArrayList<Author>();
private int qtyInStock = 0;
public Book(String name, double price) {
this.name = name;
this.price = price;
}
public Book(String name, double price, int qtyInStock) {
this.name = name;
this.price = price;
this.qtyInStock = qtyInStock;
}
public String getName() {
return this.name;
}
public double getPrice() {
return this.price;
}
public Collection<Author> getAuthors() {
return authors.values();
}
public void setPrice(double price) {
this.price = price;
}
public int getQtyInStock() {
return this.qtyInStock;
}
public void setQtyInStock(int qtyInStock) {
this.qtyInStock = qtyInStock;
}
public void printAuthors() {
authors.values().forEach(System.out::println);
}
public void addAuthor(Author author)
{
authors.put(author.getName(name), author);
}
public void removeAuthorByName(String name) {
authors.remove(authors.get(name));
}
public void removeAuthorByEmail(String email){
authors.remove(authors.get(email));
}
public void removeAuthor(String author){
authors.remove(authors.get(author));
}
public String toString() {
return "'" + name +"' by " + authors + " authors";
}
}
test cases
Author a = new Author("Adam", "adam#gmail.com", 'm');
Author b = new Author("Ben", "ben#gmail.com", 'm');
Author c = new Author("Calvin", "calvin#gmail.com", 'm');
Author d = new Author("Danielle", "Danielle#gmail.com", 'f');
Book book1 = new Book("The House", 70.00, 5);
book1.addAuthor(a);
book1.addAuthor(b);
book1.addAuthor(c);
book1.addAuthor(d);
book1.removeAuthorByName("Ben");
System.out.println(book1);
book1.printAuthors();
output:
The House by 3 authors
Adam
Calvin
Danielle
Added the UML on this link : https://gyazo.com/4afc1bafa03210044fafe06650859cb0
I suggest to change the arraylist to HashMap.
private ArrayList<Author> authors = new ArrayList<Author>();
to
private Map authors = new HashMap<String, Author>();
Change below methods-
public Collection<Author> getAuthors() {
return authors.values();
}
public void printAuthors() {
authors.values().forEach(System.out::println);
}
public void addAuthor(Author author)
{
authors.put(author.getName(), author);
}
public void removeAuthorByName(String authorName) {
authors.remove(authors.get(authorName));
}
Related
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;
}
I have an array list that is made up of different types. I want to use the get method in the array list to extract only one element from a specified index
public BookCollection() {
collection = new ArrayList<Book>(10);
}
public void addbook(String title, String author, int year, double cost, boolean Available) {
Book a = new Book(title, director, year, cost, Available);
collection.add(a);
}
In the above code I want to create a library of books but then at some point I only want the title.
public static void main(String[] args) {
BookCollection library = new BookCollection();
library.addbook("Pride & Prejudice", "Jane Austen", 1801, 24.95, true);
System.out.println(collection.get(0).toString())
}
Then I want to get just the title. So in this case it would be Pride & Prejudice. At the moment the out output is "Pride & PrejudiceJane Austen180124.95"
But I want it to be just "Pride & Prejudice".
collection.get(0).getTitle()
?
Gygabyte's answer is right. You should create getter methods in your Book class for every field, so you can call separately whenever you want.
You should also check Java rules and conventions, in this particular case, variable and method names should start with a lowercase letter, so you should switch from "Available" to "available".
Uppercase letters are for Classes.
I tried your code and found a solution, hope it will be right for you:
This is BookCollection class:
public class BookCollection extends ArrayList<Book>{
private static final long serialVersionUID = 1L;
private ArrayList<Book> collection;
public BookCollection() {
this.collection = new ArrayList<Book>();
}
public void addbook(String title, String author, int year, double cost, boolean available) {
Book a = new Book(title, author, year, cost, available);
this.add(a);
}
public static void main(String[] args) {
BookCollection library = new BookCollection();
library.addbook("Pride & Prejudice", "Jane Austen", 1801, 24.95, true);
System.out.println(library.get(0).isAvailable());
}
}
And this is Book class, with getters and setters:
public class Book {
private String name;
private String author;
private int year;
private double cost;
private boolean available;
public Book(String name, String author, int year, double cost, boolean available){
this.name = name;
this.author = author;
this.year = year;
this.cost = cost;
this.available = available;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public double getCost() {
return cost;
}
public void setCost(double cost) {
this.cost = cost;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
}
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.
this is main method
public static void main(String[] args) {
Author[] authors=new Author[2];
for(int i=0;i<=authors.length;i++);
authors[0]=new Author("suru","suru#qwe.com","m");
authors[1]=new Author("aksh","aksh#qwe.com","m");
for(int i=0;i<=authors.length;i++);
System.out.println(authors);
Book book=new Book("java",authors,200,2);
System.out.println(book);
now i created 2nd class authoer with getter and setter
private String name;
private String email;
private String gender;
public Author (String name,String email, String gender)
{
this.name=name;
this.email=email;
this.gender=gender;
}
noow i created new class Book
public class Book {
private String name;
private Author[] author;
private double price;
private int qty=0;
public Book(String name,Author[] author,double price, int qty) {
this.name=name;
this.author=author;
this.price=price;
this.qty=qty;
}
when i run this program the output give the memory adress ho can i print theese detail
You need to override toString() method in the class Author.
For example:
#Override
public String toString() {
return "Author [name=" + name + ", email=" + email + ", gender=" + gender + "]";
}
When you pass as argument of the method System.out.println() name of variable, method toString() of the class of that variable is being called. If you don't override that method in class Author or Book, toString() method inherited by these classes from Object class is being called (all classes in Java inherit from Object class). By default, this method prints address in memory for classes with toString() not defined in their bodies. There is a simple example, how you can override it in Author method:
class Author {
#Override
public String toString() {
return "Author name: " + this.name + "\nAuthor email: " + this.email + "\nAuthor gender : " + this.gender;
}
To print contents of an array (in your example to print each Author contained in Author[] authors) you might want to use one of these way to achieve that (as Author[] or Book[] is actually a type of array and not a type of Book or Author and has its own toString() method printing address in memory) :
Create a loop iterating over each element of authors array:
for (Author author : authors) {
System.out.println(author + "------"); // toString() method of each Author is called and added simple separator
}
Call Arrays.toString(authors) method. Class Arrays is provided to let you manipulate arrays in many different ways. You can read about this class in Java API documentation. This is a part of what documentation says about Arrays.toString() method:
Returns a string representation of the contents of the specified array. If the array contains other arrays as elements, they are converted to strings by the Object.toString() method inherited from Object, which describes their identities rather than their contents.
package oops;
public class Main {
public static void main(String[] args) {
Author[] authors=new Author[2];
for(int i=0;i<=authors.length;i++);
authors[0]=new Author("suru","suru#qwe.com","m");
authors[1]=new Author("aksh","aksh#qwe.com","m");
for(int i=0;i<=authors.length;i++);
System.out.println(authors);
Book book=new Book("java",authors,200,2);
System.out.println(book);
}
}
package oops;
public class Author {
private String name;
private String email;
private String gender;
public Author (String name,String email, String gender)
{
this.name=name;
this.email=email;
this.gender=gender;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String toString() {
return name+ " " +email+ " " +gender+ " ";
}
package oops;
public class Book {
private String name;
private Author[] author;
private double price;
private int qty=0;
public Book(String name,Author[] author,double price, int qty) {
this.name=name;
this.author=author;
this.price=price;
this.qty=qty;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public String getName() {
return name;
}
/*public Author[] getAuthor() {
return author;
} */
public Author[] getAuther() {
for (int i=0;i<=author.length;i++);
return author;
}
public String toString() {
return name+" "+author+" "+price+" "+qty+" ";
}
public Author[] getAutherNames() {
for (int i=0;i<=author.length;i++);
return author;
}
}
this is my full program
You an override toString() or you can print the attributes of the object directly as follows:
Book b = new Book(/*args*/);
System.out.println("Name: " + b.name);
// continue printing all the attributes in the same way
You can try this instead of overriding toString() method in the object class.
Hope this helps...
I am trying to return some values of some objects by using getter and setter method. Now I can't return more than one value inside a single method. In this case, do I need to create different methods for each return. If not, how could I solve it?
My code:
package books;
public class BooksObject {
//variable for book 1
String name1 = "The brief history of time";
String isbn1 = "111";
String[] authName1 = {"S. Hawking", " Hawking's friend"};
//variable for book 2
String name2 = "100 years of solitude";
String isbn2 = "222";
String[] authName2 = {"G. Marquez", "Marquezs friend"};
//All setters
public void setBook1(String n_1, String i_1, String[] a_N1) {
name1 = n_1;
isbn1 = i_1;
String[] authName1 = a_N1;
}
public void setBook2(String n_2, String i_2, String[] a_N2) {
name2 = n_2;
isbn2 = i_2;
String[] authName2 = a_N2;
}
//All getters method
public String getBook1() {
return name1;
//return isbn1; //shows error
//return String[]authName1;//Shows error
}
}
[Note: Of course I am going to call all these method in my main class. I just haven't posted it here.]
You should create a Book class that contains the 3 properties, and your getter would return a Book instance.
Instead of
String name1 = "The brief history of time";
String isbn1 = "111";
String[] authName1 = {"S. Hawking", " Hawking's friend"};
You'll have
Book book1 = new Book ("The brief history of time", "111", {"S. Hawking", " Hawking's friend"});
Then :
public Book getBook1() {
return book1;
}
You can further improve your BooksObject by having a books array (Book[]) instead of a different variable for each Book. Then you wouldn't need a separate getBooki method for each book.
I think you shoul change your code as shown below:
public class Book
{
private String name;
private String isbn;
private String[] authors;
/* constructor */
public Book(String name, String isbn, String[] authors) {
this.name = name;
this.isbn = isbn;
this.authors = authors;
}
/* setter */
public void setName(String name) {
this.name = name;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public void setAuthors(String[] authors) {
this.authors = authors;
}
/* getter */
public String getName() {
return name;
}
public String getIsbn() {
return isbn;
}
public String[] getAuthors() {
return authors;
}
}
public class Main
{
public static void main(String[] args) {
Book book1 = new Book(
"The brief history of time",
"111",
new String[]{"S. Hawking", " Hawking's friend"}
);
Book book2 = new Book(
"100 years of solitude",
"222",
new String[]{"G. Marquez", "Marquezs friend"}
);
}
}