I'm fairly new to coding so just wondering if someone can point me in the right direction. I'm looking to set up a Library class containing an array or array list of Book objects that carry out appropriate functions such as adding a Book, editing a Books details, deleting a Book, returning a Book and loaning a Book.
So far I have created the following Book class
//Instance variables
private int BookID;
private String Title;
private String Author;
private boolean On_Loan;
private int Number_of_Loans;
//Constructor
public Book(int BookID, String Title, String Author, boolean On_Loan, int Number_of_Loans){
this.BookID = BookID;
this.Title = Title;
this.Author = Author;
this.On_Loan = On_Loan;
this.Number_of_Loans = Number_of_Loans;
}
//Mutator methods
public void setBookID(int BookID){
this.BookID = BookID;
}
public void setTitle(String Title){
this.Title = Title;
}
public void setAuthor(String Author){
this.Author = Author;
}
public void setOn_Loan(boolean On_Loan){
this.On_Loan = On_Loan;
}
public void setNumber_of_Loans(int Number_of_Loans){
this.Number_of_Loans = Number_of_Loans;
}
//Accessor methods
public int getBookID(){
return BookID;
}
public String getTitle(){
return Title;
}
public String getAuthor(){
return Author;
}
public boolean getOn_Loan(){
return On_Loan;
}
public int getNumber_of_Loans(){
return Number_of_Loans;
}
}
You need an ArrayList<Book> object! To create one:
ArrayList<Book> books = new ArrayList<> ();
To add an item to it,
books.add (yourBookObjectToBeAdded);
To change the books' properties, you need to get the book first,
books.get(theIndexOfTheBook);
It is recommended to store the book in a variable:
Book myBook = books.get(theIndexOfTheBook);
And then you can use one of the mutators (setters),
myBook.setOn_Loan (true);
Advantages:
unlike arrays, ArrayList is dynamic in size.
It is generic, you don't need to cast stuff.
And that is basically a guide to using array lists. Now you want to make a class that do all this stuff. So it must contain an ArrayList<Book>:
public class Library {
private ArrayList<Book> books
public Library () {
books = new ArrayList<> ();
}
public ArrayList<Book> getBooks () {
return books;
}
}
Then the user can get the books and do operations on the array list.
Alternatively, you can make it more abstract. You can add borrowBook, returnBook, editBook and other methods to the class. For example, the borrowBook method would be like this:
public void borrowBook (int bookIndex) {
Book book = books.get(bookIndex);
book.setOn_Loan (true);
}
first, you will have to create the Book object
then you can create an array of Book objects like this
Book[] books = new Book[10]; //fixed list of size 10
Book b1 = new Book(); // create a book object
books[0] = b1; // assign it to be the first array element
or an arraylist list like this
ArrayList<Book> books = new ArrayList<Book>(); //initial empty list, no fixed size
Book b1 = new Book(); // create a book object
books.add(b1); // append it to the list
If their is a variable number of books, using an ArrayList will be a good choice, as you can add more books on the fly, unlike an array, where you have to fix the size.
To create an ArrayList of Book objects, use: ArrayList<Book> books = new ArrayList<Book>();
To add a book to the list: books.add(new Book());
To perform a command on a book (i.e. edit the details), you need to know the index of the book, or you could go through all of them. You can do this using the .get(index) command, for example:
books.get(index).doSomething();
You can read more about ArrayLists and all of their methods here, and a simple tutorial could be found here.
Related
I have two classes ("Startup.java" and "Book.java").
My goal is to print all object(s) from "Book.java".
To call the view() method, I initialized a new 'book-object'. The problem is:
if I call "book.view", it print's '0nullnull0' (I know, it's because of the constructor), I have no idea how to fix it. Here you can see the code:
package array;
import java.util.*;
public class Startup{
public static void main(String[] args) {
Book book = new Book(0, null, null, 0);
book.view();
}
package array;
public class Book {
private int number;
private String title;
private String language;
private int price;
public Book(int number, String title, String language, int price) {
this.number = number;
this.title = title;
this.language = language;
this.price = price;
}
public void add() {
Book b1 = new Book(1, "title", "de", 2);
}
public void view() {
System.out.println(number + title + language + price);
}
}
You have initialized your object using
Book book = new Book(0, null, null, 0);
Hence, the output is coming like that.
I think you want the values in your add method (not sure what that method is for?) to be printed.
So, you need to call your constructor with those values.
Book book = new Book(1, "title", "de", 2);
book.view();
You can print all Book objects by storing the objects in an array and then iterating through the array and call the list function for each Object of the array
Book[] bookArray=new book[n];
Add your objects to this array
Now iterating through the array you would be able to print all the objects
for(int i=0;i<n;i++) {
bookArray[i].view();
}
I have two classes, Student and Book.
I want to store book name returned by student.getBook(that will return Set<Book>) into List<String>.
Student.java
public class Student {
private int id;
private String bookName;
//Setter and getter.......
}
Student.java
public class Student {
private int id;
private String student Name;
private Set<Book> books;
//Setters and Getters
}
Here is main method
public static void main(String[] arg){
Book b1= new Book(1, "art");
Book b2= new Book(2, "science");
Book b3= new Book(3, "bio");
Set<Book> b=new HashSet<>();
b.add(b1);
b.add(b2);
b.add(b3);
Student s=new Student (1, "std1",b);
//here I want to store bookName
//into List, some thing like
List<String> book=new
ArrayList<>(s.getBooks().getBookName());
}
Please help.....
This is where the Stream API comes in handy!
To turn a set of books (s.getBooks()) directly into a List<String> with book names, you just need to map and collect.
List<String> bookNames = s.getBooks().stream()
.map(x -> x.getBookName())
.collect(Collectors.toList())
This might look new to you, so I'll explain it bit by bit.
The stream method creates a Stream<Book>. This is so that you can do cool operations, like map, reduce and filter on the Set. Then we map the stream of books. map is just another word for "transform". Because you only want the book names, we transform each book in the stream into its book name. The x -> x.getBookName() describes how we want to transform it. It means "given a book x, we get the book name of x". And finally, we call collect, which "collects" everything in the stream and puts them back in a collection. In this case we want a List so we call toList().
Since s.getBookNames() returns the Set<Book>, you must iterate over the collection to fetch individual book's name and then save it to another List in your code named as book :
List<String> bookNames = new ArrayList<>(); // initialize a list for all the book names
s.getBooks().forEach(book -> bookNames.add(book.getBookName())); // iterate all the books and add their names to the above list
Also, this assumed few obvious things as pointed in comments as well,
private String student Name; // this variable either named as 'student or `name` or `studentName`
and the first model is for the Book.java instead of Student.java.
Someway, I see your modal definition for student is not good. Simply you can define Student modal as follow.
And create a separate public method in Student class to fetch the booknames.
public class Student {
private int id;
private String name;
private Set<Book> books;
public Student(int id, String name, Set<Book> b) {
this.id = id;
this.name = name;
this.books = b;
}
// all getter and setter.
public List<String> getBookNames(){
return this.getBooks().stream().map(x -> x.getName()).collect(Collectors.toList());
}
}
if you are using java1.8, as sweeper suggested you can use stream api to do your work.
public static void main(String[] args) {
Book b1 = new Book(1, "art");
Book b2 = new Book(2, "science");
Book b3 = new Book(3, "bio");
Set<Book> b = new HashSet<>();
b.add(b1);
b.add(b2);
b.add(b3);
Student s = new Student(1, "std1", b);
List<String> books = s.getBookNames();
System.out.println(books);
}
I am currently working on an inventory program involving a one dimensional array, 2 classes (Store and Book), and several other things such as methods and a constructor.
The Store class which is the main class I guess you could say is supposed to include the main() method, and is supposed to read a list of purchases from a file, process each purchase with an appropriate message (ISBN number, amount, price, or problem (such as out of stock or do not have)), store an array of up to 15 books of type Book, a method to read in the inventory file, method to process a purchase, a method to print the inventory at closing along with the number of books sold and amount made at closing.
The Book class includes, book objects (each book object holds ISBN String, price double, and copies int), constructor, getters and setters, and a method to print the information.
Since the array is supposed to be created in the Store class, but be of type Book and made up of the book objects (I'm assuming?), I'm having trouble figuring out how to do this properly (assigning values to the isbn, price, copies variables, setting up the constructor correctly, etc).
Update
The main issue I'm having right now is being able to print the book object from my printInfo method. I am getting an error message at the print statement of that method stating "cannot find symbol. symbol: book". I can't really see if the program is actually working yet since that's kind of what I need to see at this point (the printed out book object) before I start adding in a few more methods to do other things that depend on this book object being correct.
Here is the code I have come up with so far:
The Store class:
import java.util.Scanner;
import java.io.*;
public class Store {
public static void main(String[] args) throws Exception {
Book[] books = readInventory();
for (Book : books) {
System.out.printf("ISBN: %s, Price: %f, Copies: %d%n",
book.getISBN(), book.getPrice(), book.getCopies());
}
}
public static Book[] readInventory() throws Exception {
Book[] books = new Book[15];
java.io.File file = new java.io.File("../instr/prog4.dat");
Scanner fin = new Scanner(file);
String isbn;
double price;
int copies;
while (fin.hasNext()) {
for(int i = 0; i < books.length; i++) {
isbn = fin.next();
price = fin.nextDouble();
copies = fin.nextInt();
Book book = new Book(isbn, price, copies);
books[i] = book;
}
}
fin.close();
return books;
}
public static void printInfo(Book[] books) {
System.out.println(book);
}
}
And here is my Books Class:
public class Book {
private String isbn;
private double price;
private int copies;
public Book(String isbnNum, double priceOfBook, int copiesInStock) {
isbn = isbnNum;
price = priceOfBook;
copies = copiesInStock;
}
public String getISBN() {
return isbn;
}
public double getPrice() {
return price;
}
public int getCopies() {
return copies;
}
public void setISBN(String isbn) {
this.isbn = isbn;
}
public void setPrice(double price) {
this.price = price;
}
public void setCopies(int copies) {
this.copies = copies;
}
#Override
public String toString() {
return String.format("ISBN: %s, Price: %f, Copies: %d%n",
this.getISBN(), this.getPrice(), this.getCopies());
}
}
This is my first time working with classes, or at least creating multiple classes in the same program, so I'm still trying to figure out how this works. I've been reading a tutorial I found online that has been somewhat helpful, but I'm having trouble applying it to this specific type of program.
Any suggestions would be greatly appreciated.
Hi glad to see you've made the effort to actually try something before jumping on here. What you have done is pretty good so far. But what you really need now is a getter and setter method in your class Book. These will allow you to return or set the value of the variable for the object.
public class Book {
private String isbn;
private double price;
private int copies;
public Book(String isbnNum, double priceOfBook, int copiesInStock) { // Constructor?
isbn = isbnNum;
price = priceOfBook;
copies = copiesInStock;
}
public String getISBN() {
return this.isbn;
}
public double getPrice() {
return this.price;
}
public int getCopies() {
return this.copies;
}
public void setISBN(String value) {
this.isbn = value;
}
public void setPrice(double value) {
this.price = value;
}
public void setCopies(int value) {
this.copies = value;
}
}
This should help you get on the right track. Depending on how you want the information to come up would depend on whether you add System.out.println("ISBN: " + this.isbn); and so on in each get function, or you could declare a separate function getInfo which simply prints each. Or if you were returning it into store you could always print it that way. One more thing to note is that you have been declaring books as Book[] books = new Book[15] as you are creating an array of Book objects and not strings. If you need any more help let me know.
1.you shouldn't use String Array.you should declare Book Array instead. then It will be easier to assign your Book object.
for example
Book[] books = new Book[15];
books[i] = new Book(isbnNum,priceOfBook,copiesInStock);
2.because variable in Book class was declare in private type. you should create get methods in your Book class to get variable in any object.
for example
public String getbnNum()
{
return isbn;
}
public double getprice(){
return price;
}
public int getcopies(){
return copies;
}
I wrote comments in the code for you. I have to assume your file-reading code is correct since I don't have the file.
import java.util.Scanner;
public class Store {
/*
* This is the main method. It is where the code that starts off the
* application should go.
*/
public static void main(String[] args) throws Exception {
// Here, we take the array returned by the method and set it to a local variable.
Book[] books = readInventory();
// This is an alternative notation than a normal for-loop.
for (Book book : books) {
System.out.printf("ISBN: %s, Price: %f, Copies: %d%n",
book.getISBN(), book.getPrice(), book.getCopies());
}
/* Alternative to above.
for (int i = 0; i < books.length; i++) {
Book book = books[i];
System.out.printf("ISBN: %s, Price: %f, Copies: %d%n",
book.getISBN(), book.getPrice(), book.getCopies());
}
*/
}
// We add the return type of Book[] so we can get a reference to our array.
public static Book[] readInventory() throws Exception {
Book[] books = new Book[15];
java.io.File file = new java.io.File("../instr/prog4.dat");
Scanner fin = new Scanner(file);
// These variables don't need to be initialized yet.
String isbn;
double price;
int copies;
while (fin.hasNext()) {
// Fill the books array with Book objects it creates from the file.
for (int i = 0; i < books.length; i++) {
isbn = fin.next();
price = fin.nextDouble();
copies = fin.nextInt();
Book book = new Book(isbn, price, copies);
books[i] = book;
}
}
fin.close();
return books;
}
}
Book class:
public class Book {
private String isbn;
/*
* Careful using double as your type for variables that hold money values.
* If you do any division, you can end up getting answers different than
* what you might expect due to the way Java handles remainders. For that,
* make price a Currency type, which you can import from Java.util
*/
private double price;
private int copies;
public Book(String isbnNum, double priceOfBook, int copiesInStock) {
isbn = isbnNum;
price = priceOfBook;
copies = copiesInStock;
}
// This is an example of a getter method, which we need since our isbn is
// declared as private. Now, other methods can still read what isbn is.
public String getISBN() {
return isbn;
}
public double getPrice() {
return price;
}
public int getCopies() {
return copies;
}
/*
* We can use the "this" keyword to refer to this instance's isbn variable,
* instead of the local variable isbn that was passed to the method.
* Therefore, in this tricky notation we are setting the object's isbn
* variable to the isbn variable passed to the method.
*/
public void setISBN(String isbn) {
this.isbn = isbn;
}
public void setPrice(Double price) {
this.price = price;
}
public void setCopies(int copies) {
this.copies = copies;
}
}
Also note that a more advanced way to print the information for each book would be to make a toString() method in the Book class which overrides the default toString method it inherits from the generic Object class. You should use a special convention called an override annotation to do this as it is considered good practice when we redefine methods from a superclass (Object is a superclass of all objects, including Book).
#Override
public String toString() {
return String.format("ISBN: %s, Price: %f, Copies: %d%n",
this.getISBN(), this.getPrice(), this.getCopies());
}
That would allow us to simply call System.out.println(book);, for example, and would also mean we wouldn't have to rewrite all of this code every place we want to print a book. This is an important principle with objects—they generally should take care of themselves.
short question. Hopefully it gets answered pretty fast. Lets say I have a singleton like this:
package main.library;
public enum LibrarySingleton {
INSTANCE(new String[][]{});
final String[][] bookStore;
private LibrarySingleton(String[][] bookStore){
this.bookStore = bookStore;
}
}
and a Book class that holds 3 variables:
package main.library;
public class Book{
String author;
String title;
int pages;
#Override public String toString(){
return ("|" + author + "|" + title + "|" + pages + "|");
}
public Book(){
System.out.println("Error: No book information specified");
}
public Book(String author, String title, int pages){
this.author = author;
this.title = title;
this.pages = pages;
}
public String getAuthor(){
return author;
}
public String getTitle(){
return title;
}
public int getPages(){
return pages;
}
}
I'm looking on how to use that singleton as an array holding books. How can I access the books, throw them into the array (singleton), or remove them from the array (singleton)? In case the singleton should be written differently, please correct me, and explain why is it wrong, as I'm not so "premium" with Java yet.
Really hope you guys are going to answer me on that. Just the questions please.
If you want singleton, you can use following approach:
public class Library {
private static final Library instance = new Library();
private List<Book> books = new ArrayList<Book>();
public static Library getInstance() {
return instance ;
}
public void add(Book book) {
books.add(book);
}
}
Of course, add synchronization if your program has multiple threads. And if your program runs in J2EE environment, where complex classloading occurs, you need a different pattern.
If you initialize an empty array and make it final it will stay empty and you cannot reinitialize it. I guess what you need is an arraylist (list in general). That one you can initialize and add element to it.
I cannot grasp the usage of those constructors.
I understand that one is as follows:
public book(){
private string author;
private string title;
private int reference;
}
And a parametrised constructor is as follows:
public book( string author, string title, int reference){
}
However how would this be used in a main method?
There are three ways you can have a constructor:
1) You declare a no-parameter one
.
public class book
{
string author;
string title;
int reference;
public book() {
// initialize member variables with default values
// etc.
}
}
2) You declare one with parameters
.
public class book
{
string author;
string title;
int reference
public book(string author, string title, int reference) {
// initialize member variables based on parameters
// etc.
}
}
3) You let the compiler declare one for you -- this requires you do not declare one of your own. In this case the member variables will be provided a default value based on their type (essentially their no-parameter constructor called)
You can mix options 1) and 2), but 3) is stand-alone (cannot mix it with any of the other two). You can also have more than one constructors with parameters (the parameter types/numbers must be different)
An example use:
public static void main(String[] args) {
String author = ...;
String title = ...;
int ref = ...;
book book1 = new book(); // create book object calling no-parameter version
book book2 = new book(author, title, ref); // create book object calling one-parameter
// (of type String) version
}
Pro grammatically, how to use them...
book b1 = new book();
book b2 = new book("My Title", "My Author", 0);
You call the first one to create an empty book. There's probably setTitle(String title), setAuthor(String author) and setReference(int ref) methods, as well. This would look like...
book b1 = new book();
// do stuff to get title author and reference
b1.setTitle(title);
b1.setAuthor(author);
b1.setReference(reference);
You'd call this one if you didn't have the title, author, and reference available when you were constructing the book instance.