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.
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;
}
How do I print the album title from the array-list if the contents of the object is in a private field in another class?
Display Method
public void displayAllAlbums() {
for (int i = 0; i < AlbumList.size(); i++) {
System.out.println(AlbumList.get(i));
}
}
Album Class that has private variables title and price.
class Album {
private String title;
private double price;
Album(String title, double price) {
this.title = title;
this.price = price;
}
public String getTitle() {
return this.title;
}
public double getPrice() {
return this.price;
}
}
Cart Class adds songs to arraylist can also get total
import java.util.*;
public class Cart {
List<Album> AlbumList = new ArrayList<Album>();
Main Method putting albums into addAlbum method
public static void main(String[] args) {
Cart cart1 = new Cart();
Album album1 = new Album("ye", 20);
Album album2 = new Album("MBDTF", 16);
cart1.addAlbum(album1);
cart1.addAlbum(album2);
System.out.println(cart1.getTotalAlbums());
cart1.displayAllAlbums();
}
adding album to the arralist
public void addAlbum(Album album) {
AlbumList.add(album);
}
Unsure on how to display the album
public void displayAllAlbums() {
for (int i = 0; i < AlbumList.size(); i++) {
System.out.println(AlbumList.get(i));
}
}
Do this.
public void displayAllAlbums() {
for (int i = 0; i < AlbumList.size(); i++) {
Album album = AlbumList.get(i)
System.out.println(album.getTitle() + " "+ album.getPrice());
}
}
Your Arraylist's objects are actually Album object. So when are accessing an ArrayList object via AlbumList.get(i) command, you're getting an Album object instance. So you pass it on to Album variable. Then access the private field via getter methods you've set up earlier!
Cheers!
You can do this either by overriding toString() method in Album class or by providing a public method for displaying the properties.
class Album {
private String title;
private double price;
Album(String title, double price) {
this.title = title;
this.price = price;
}
public String getTitle() {
return this.title;
}
public double getPrice() {
return this.price;
}
#Override
public String toString(){
return "title:"+title+",price:"+price;
}
}
While you passing the object to System.out.println(AlbumList.get(i)), the toString() method will get invoke and print album title and price.
How do I print the album title from the array-list
Just use the public accesor method i.e. Album#getTitle()
public void displayAllAlbums() {
for (Album album : AlbumList) {
System.out.printf("Album title: %s%n",album.getTitle());
}
}
(I'm a beginner so this may sound obvious/lack information.) I have an ArrayList of attributes for different pets including attributes such as their given-name, common-name, the price of the animal, sex, date bought and date sold. this information is generated from a separate class that adds an array of information to an array of arrays of the already existing list of animals. Essentially, I want to send the array to another class (called Pets) so it can then be added to the array of arrays. I understand this may sound confusing but this is the only way I can word it, I can clarify anything if needed. Any help would be great as I'm really stuck and can't work out how to send it. This is the code that generates my values in the array (using text-boxes to input the information).
public void actionPerformed(ActionEvent e) {
ArrayList<String> NewanimalArr = new ArrayList<>();
String givenName = txtGivenname.getText();
String commonName = txtCommonName.getText();
String priceOf = txtPrice_1.getText();
String sexOf = txtSex.getText();
String colourOf = txtMaincolour.getText();
String dateOfA = txtArrivaldate.getText();
String dateSold = txtSellingdate.getText();
NewanimalArr.add(givenName);
NewanimalArr.add(commonName);
NewanimalArr.add(priceOf);
NewanimalArr.add(sexOf);
NewanimalArr.add(colourOf);
NewanimalArr.add(dateOfA);
NewanimalArr.add(dateSold);
System.out.println(NewanimalArr);
}
});
this will then print information generated that is entered for example:
[alex, Dog, 40.50, Male, Brown, 14/04/2015, 14/12/2016]
how do I then send this data to another class
Option one Constructor Injection:
public class Foo {
List<String> actionPerformed(ActionEvent e) {
List<String> newanimalArr = new ArrayList<>();
.....
return newanimalArr
}
...
public class Pets {
private final List<String> array;
public Pets(final List<String> array) {
this.array = array;
}
void bar() {
System.out.println(this.array);
}
}
....
public static void main(String[] args) {
Foo foo = new Foo();
Pets pets = new Pets(foo.actionPerformed( new ActionEvent() ) );
pets.bar();
}
Option two Getter-Setter Injection:
public class Foo {
private final List<String> newanimalArr;
public Foo() {
this.newanimalArr = new ArrayList<>();
}
public void actionPerformed(ActionEvent e) {
.....
}
public List<String> getNewanimalArr() {
return new ArrayList<String>(newanimalArr);
}
}
...
public class Pets {
private List<String> array;
public Pets() {
this.array = Collections.<String>emptyList();
}
public void setArray(final List<String> array) {
this.array = array;
}
public void bar() {
System.out.println(this.array);
}
}
....
public static void main(String[] args) {
Foo foo = new Foo();
foo.actionPerformed( new ActionEvent() );
Pets pets = new Pets();
bar.setArray( foo.getNewanimalArr() );
pets.bar();
}
See also Dependency Injection Patterns
Create a class definition of Pet, using instance variables for the fields. In Java it is custom to create a setXyz and a getXyz for each xyz field. You can also create a constructor in which you pass all the values and assign them to the fields, this minimizes the risk of fields not being filled in.
The initial ArrayList you are creating doesn't add that much use, it is easier to create the Pet instances directly:
List<Pet> newArrivals = new ArrayList<>();
// get data from view fields and if necessary transform them to other objects such as:
LocalDate arrivedOn = LocalDate.parse(txtArrivaldate.getText(), DateTimeFormatter.ofLocalizedDate(FormatStyle.FormatStyle);
// create and add a new Pet object to the list
newArrivals.add(new Pet(.....));
public class Pet {
public enum Gender {
FEMALE, MALE
}
private String givenName;
private String commonName;
private double price;
private Gender gender;
private String color;
private LocalDate arrivedOn;
private LocalDate soldOn;
public Pet() {
}
public Pet(String givenName, String commonName, double price, Gender gender, String color, LocalDate arrivedOn,
LocalDate soldOn) {
super();
this.givenName = givenName;
this.commonName = commonName;
this.price = price;
this.gender = gender;
this.color = color;
this.arrivedOn = arrivedOn;
this.soldOn = soldOn;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getCommonName() {
return commonName;
}
public void setCommonName(String commonName) {
this.commonName = commonName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public LocalDate getArrivedOn() {
return arrivedOn;
}
public void setArrivedOn(LocalDate arrivedOn) {
this.arrivedOn = arrivedOn;
}
public LocalDate getSoldOn() {
return soldOn;
}
public void setSoldOn(LocalDate soldOn) {
this.soldOn = soldOn;
}
}
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));
}
I am trying to finish my home assignment for programming class, unfortunately getting stuck through half of it ,due to my stupidity. ArrayList that I have created overwrites 0 index constantly.
Here are my classes for creating invoices:
import java.util.ArrayList;
public class Order
{
private String customerName;
private ArrayList<LineItem> items = new ArrayList<LineItem>();
public Order(String customerName)
{
this.customerName = customerName;
}
public String getCustomerName()
{
return customerName;
}
public ArrayList<LineItem> getItems()
{
return this.items;
}
public double getOrderTotal()
{
double totalOrder = items.get(0).getTotalPrice();
return totalOrder;
}
public void addItem(String description,double unitPrice, int quantity)
{
LineItem object = new LineItem(description,unitPrice,quantity);
items.add(object);
}
public String toString()
{
String.format("%n%-20s%-15s%-15f%-15f",items.get(0).getDescription(),
items.get(0).getQuantity(),items.get(0).getUnitPrice(),getOrderTotal());
return p;`
}
}
public class LineItem
{
private String description;
private double unitPrice;
private int quantity;
public LineItem(String description,double unitPrice, int quantity)
{
this.description = description;
this.unitPrice = unitPrice;
this.quantity = quantity;
}
public String getDescription()
{
return this.description;
}
public double getUnitPrice()
{
return this.unitPrice;
}
public int getQuantity()
{
return this.quantity;
}
public double getTotalPrice()
{
return this.unitPrice * this.quantity;
}
public String toString()
{
return String(this.description,this.unitPrice,this.quantity)
}
}
AND a part of ... while LOOP for main class
do
{
customerName = AssignmentHelper.getRequiredStringInput("Please enterthe customer's name: ","A customer name must be entered!");
newOrder = new Order(customerName);
newOrder.addItem(description,unitPrice,quantity);
} while(Character.toString(userAnswer).equalsIgnoreCase ("Y"));
Your loop creates a new Order object in each iteration :
newOrder = new Order(customerName);
Each Order object has a new empty ArrayList, which is why it seems the first index is always overwritten.
If you want a single ArrayList to hold all the items, you should create a single Order object prior to the do-while loop.
newOrder = new Order(customerName);
do {
...
newOrder.addItem(description,unitPrice,quantity);
} while(Character.toString(userAnswer).equalsIgnoreCase ("Y"));
In the loop, a new order object is created which has two fields (customer name and an Arraylist of line items). Initially the ArrayList will be empty.The call to addItem object creates a new Lineitem object and add its to the ArrayList items. Therefore the lineItem object will always be added to index zero.
Create a new object only when a new customer is added.You can have a HashMap where key is the customer name. If the key already exists add to the same object else create a new order object and it to the Map.