Issue with a method for a library of objects - java

I'm trying to make a program that creates a library of different books, I have set a number of copies for each item in the library and every time I check out an Item I want it to deduct 1 copy from only the particular object I check out but instead it takes a copy away from all the objects. not sure how to fix the problem.
public abstract class Item{
private int identify;
private String title;
private int copies;
public Item(){
identify=0;
title="N/A";
copies=0;
}
public Item(int id, int copy, String t){
identify=id;
copies=copy;
title=t;
}
public void setIdentificationNumber(int id){
identify = id;
}
public void setTitle(String t){
title=t;
}
public void setNumberCopies(int num){
copies=num;
}
public int getIdentificationNumber(){
return identify;
}
public String getTitle(){
return title;
}
public int getNumberCopies(){
return copies;
}
public void checkOut(){
if(copies>0){
copies-=1;
System.out.println("You have checked out "+title+". Thank You");
}
else{
System.out.println("All copies of "+title+" are checked out!");
}
}
public void checkIn(){
copies+=1;
}
}
The problem may also be in my client method I have posted the code for that as well below.
import java.util.Arrays;
import java.util.Scanner;
public class Library{
static String title;
static String author;
static int id;
static int copies;
static String date;
static Book[] database = new Book[100];
static int count=0;
public static void main(String[] args){
int i;
Scanner s = new Scanner(System.in);
do{
addBook();
System.out.println("would you like to add another book?");
i=s.nextInt();
}while(i == 0);
database[0].viewDetails();
database[1].viewDetails();
checkingOut();
database[0].viewDetails();
database[1].viewDetails();
}
public static void addBook(){
Scanner s = new Scanner(System.in);
System.out.println("Enter the title of the book you want to add to the collection");
title=s.nextLine();
System.out.println("Enter the author of the book you want to add to the collection");
author=s.nextLine();
System.out.println("Enter the publishing date of the book you want to add to the collection");
date=s.nextLine();
System.out.println("Enter the ID number of the book you want to add to the collection");
id=s.nextInt();
System.out.println("Enter the the number of copies that will be added into the collection");
copies=s.nextInt();
Book Book1 = new Book(date, author, copies, id, title);
database[count] = Book1;
count++;
}
public static void checkingOut(){
boolean found=false;
int idSearch;
int i=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the ID number of the book you want to check out");
idSearch=s.nextInt();
while(i<database.length && found!=true){
if(database[i].getIdentificationNumber() == idSearch){
found = true;
}
i++;
}
if(found==true){
database[i].checkOut();
System.out.println("There are "+database[i].getNumberCopies()+" copies left");
}
else{System.out.println("There is no book with that ID number!");}
}
}
In my addBook method I create a new object called book1 every time I make a new book, so I think that it may be changing all of the book objects every time I add a book. I'm not really sure of a better way to write the method.
here is my method for book also
public class Book extends WrittenItem{
public Book(){
super();
}
public Book(String date, String a, int copy, int id, String t){
super(a, date, copy, id, t);
}
public void viewDetails(){
System.out.println("ID: "+getIdentificationNumber()+"\nTitle: "+getTitle()+"\nAuthor: "+getAuthor()+" Date written: "+getDate()+"\nCopies available: "+getNumberCopies());
}
}
Any help would be greatly appreciated.

I can't 100% tell from your code, but I'm assuming Book extends Item. In that case, try something like this for Book constructor
public class Book extends Item {
String author;
String date;
public Book(String date, String author, int copies, int id, String title) {
super(id, copies, title); // Item constructor matches this super() call
// public Item(int id, int copy, String t)
this.author = author;
this.date = date;
}
}
You want Book to have the same copies at Item. So when you checkOut(), the Item number equals you input from the Book constructor. If you don't put the super() in the constructor, your Item copies will remain 0 and you will always get System.out.println("All copies of "+title+" are checked out!"); because copies is never > 0.

If your book is something like this,
public class Book extends Item {
private String date;
private String author;
public Book() {
}
public Book(String date, String author, int copies, int id, String title) {
super(id, copies, title);
this.author = author;
this.date = date;
}
void viewDetails() {
System.out.println("date:" + date + " author:" + author + " copies:" + getNumberCopies() + " id:" + getIdentificationNumber() + " title:" + getTitle());
}
}
Then your code should work fine, as i've tested, if you also add a break in your checkingOut() method,
public static void checkingOut() {
boolean found = false;
int idSearch;
int i = 0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the ID number of the book you want to check out");
idSearch = s.nextInt();
while (i < database.length && found != true) {
if (database[i].getIdentificationNumber() == idSearch) {
found = true;
break; //add this
}
i++;
}
if (found == true) {
database[i].checkOut();
System.out.println("There are " + database[i].getNumberCopies() + " copies left");
} else {
System.out.println("There is no book with that ID number!");
}
}

Related

How do I match parts (title or isbn) from my book array that was created from a text file?

When I run this code, it gives an error saying cannot involve get__() on the array type Book[].. In the main method, I have a book array with the information from a text file -- title, isbn, price, qty, forsale.
public static int searchByTitleOrISBN(Book[] b)
{
int i = 0;
// print a message "Enter the Title or ISBN of the book: "
System.out.println("Enter the Title or ISBN of the book: ");
String input = scan.next();
// use a while loop to search through the array books using a counter and as long as no match is found
while (i < b.length) {
// if there's a match for the title or a match for the isbn and the book quantity > 0 and the book is for sale
if ((b.getTitle().equals(title) || b.getISBN().equals(isbn)) & b.getQty() > 0 && b.isForSale()) {
Basically what you want is to search the entire list.If you want to keep up your present implementation, then the solution given by #Jens works.
But If you go by searching one by one it would be O(n) but if you leverage inbuilt HashMaps you can do it with O(1) using hashCode and equals and no need of looping through all the objects for each and every search.
the Book class which keeps the data of the book. hashCode and equals is implemented here.
public final class Book{
private final String title;
private final String isbn;
private double price;
private int quantity;
private boolean forSale;
public final Key key;
public Book(String title, String isbn, double price, int quantity,boolean forSale){
this.title = title;
this.isbn = isbn;
this.price = price;
this.quantity =quantity;
this.forSale = forSale;
this.key = makeKey(title,isbn);
}
private static Key makeKey(String title,String isbn) {
return new Key(title,isbn);
}
public Key getKey() {
return this.key;
}
public String getTitle(){
return this.title;
}
public String getISBN(){
return this.isbn;
}
#Override
public final String toString(){
String s = this.title +"; "+ this.isbn+ "; "+this.price+"; "+this.quantity;
return s;
}
public static final class Key{
private final String title;
private final String isbn;
private Key(String title,String isbn) {
this.title = title;
this.isbn = isbn;
}
private String getTitle() {
return this.title;
}
private String getISBN() {
return this.isbn;
}
//calculates the hash of the entry, if we don't override this it will
//use the hash of the reference. so we need to change it for comparision
#Override
public final int hashCode(){
return this.title.hashCode()+this.isbn.hashCode();
}
//if two components have same hash code, then we can use extra criterion
//to check if the two objects are same. in the book case the hash is
//unique.since we are using the title and the isbn;
#Override
public final boolean equals(Object obj){
if(this==obj){
return true;
}
if(obj!=null && this.getClass()==obj.getClass()){
Key tempObj = (Key)obj;
return (this.title == tempObj.getTitle()) && (this.isbn == tempObj.getISBN());
}
return false;
}
}
}
BookMap class which stores all the book objects in form of Map<Book.Key,Book>. This will help with the easy retrival of book data.
public final class BookMap{
private final Map<Book.Key,Book> map;
private final String name;
public BookMap(String name){
this.name = name;
this.map = new HashMap<>();
}
public final String getName(){
return this.name;
}
public final Map<Book.Key,Book> getMap(){
return Collections.unmodifiableMap(this.map);
}
public final void addBook(Book book){
this.map.put(book.getKey(),book);
}
public final Book getBook(Book book){
Book.Key tempKey = book.getKey();
return this.map.get(tempKey);
}
public final boolean findBook(Book book){
if(book != null) {
return this.map.containsKey(book.getKey());
}
return false;
}
#Override
public final String toString() {
String s ="Books list : \n";
for(Map.Entry<Book.Key,Book> b:this.map.entrySet()) {
s= s+b.getValue()+"\n";
}
return s;
}
}
Now a sample Main.js with static main method to retrieve the book list.
public class Main {
public static BookMap list = new BookSet("General list");
public static void main(String[] args) {
Book temp = new Book("Journey to the center of the earth","isbn-001-002-0455",9.99,15,false);
list.addBook(temp);
temp = new Book("The Time Machine","isbn-001-002-0456",9.99,15,false);
list.addBook(temp);
temp = new Book("The War of the Worlds","isbn-001-002-0457",8.99,15,false);
list.addBook(temp);
temp = new Book("Brave New World","isbn-001-002-0458",11.99,15,false);
list.addBook(temp);
temp = new Book("Ninteen Eighty-four","isbn-001-002-0459",19.99,15,false);
list.addBook(temp);
temp = new Book("Ray Bradbury","isbn-001-002-0460",14.99,15,false);
list.addBook(temp);
temp = new Book("I, Robot","isbn-001-002-0461",12.99,15,false);
list.addBook(temp);
temp = new Book("Foundation","isbn-001-002-0462",12.99,15,false);
list.addBook(temp);
temp = new Book("The Martial Chronicles","isbn-001-002-0463",3.99,15,false);
list.addBook(temp);
temp = new Book("Fahrenheit 451","isbn-001-002-0464",6.99,15,false);
list.addBook(temp);
//testing with the book already in the list;
temp = new Book("Fahrenheit 451","isbn-001-002-0464",0,0,false);
//prints book detail
System.out.println(list.getBook(temp));
//testing with the book already in the list;
temp = new Book("I am not in the list","isbn-001-002-0464",0,0,false);
//prints null as the book is not in the list
System.out.println(list.getBook(temp));
System.out.println(list);
}
}
The above is a rough idea, you can develop more on it, i have used final for classes in order to prevent subclassing, as it would become complex with inheritence to understand and debug.i like avoiding complexity as much as i can. If some common pattern is there, then i will try to use abstract classes.
You have to acces an element in your loop not the array itself:
while (i < b.length) {
// if there's a match for the title or a match for the isbn and the book quantity > 0 and the book is for sale
if ((b[i].getTitle().equals(title) || b[i].getISBN().equals(isbn)) & b[i].getQty() > 0 && b[i].isForSale()) {

What is the relationship between two classes they are tied to a Third class?

Getting stuck with my Travail System Project, Confusing a little bit about understanding that if there Classes called Bookable, Hotel and BookingSystem.
Hotel class is implements Bookable. Furthermore, BookingSystem Class is composition from Bookable, So, I need to create method at BookingSystem class which called addHotel.
what I must do about it to make a relationship between Hotel Class and BookingSystem Class.
Thanks In Advance.
Israa
Hotal Class:
public class Hotel implements Bookable {
private String name, location;
private int noOfRooms;
private double roomPrice;
private Date bookingDate;
private ArrayList<Integer> bookedRooms = new ArrayList<Integer>();
private ArrayList<Integer> numberOfrooms = new ArrayList<Integer>();
public Hotel() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getNoOfRooms() {
return noOfRooms;
}
public void setNoOfRooms(int noOfRooms) {
this.noOfRooms = noOfRooms;
}
public double getRoomPrice() {
return roomPrice;
}
public void setRoomPrice(double roomPrice) {
this.roomPrice = roomPrice;
}
public Date getBookingDate() {
return bookingDate;
}
public void setBookingDate(Date bookingDate) {
this.bookingDate = bookingDate;
}
public ArrayList<Integer> getBookedRooms() {
return bookedRooms;
}
public void setBookedRooms(ArrayList<Integer> bookedRooms) {
this.bookedRooms = bookedRooms;
}
public String Book() {
if ( numberOfrooms.size() != (bookedRooms.size())) {
for (int i = 0; i < bookedRooms.size(); i++) {
int oldVal = bookedRooms.get(i);
int newVal = oldVal + 1;
bookedRooms.add(bookedRooms.set(i, newVal));
}
}
return null;
}
}
Bookable class:
public interface Bookable {
public String Book();
}
BookingSytsem Class:
public class BookingSystem {
private ArrayList<Customer> customer = new ArrayList<Customer>();
private ArrayList<Bookable> bookable = new ArrayList<Bookable>();
private ArrayList<Operation> operation = new ArrayList<Operation>();
public BookingSystem() {
}
// **
public void addCustomer(String name, int id) {
Customer customers = new Customer(id, name);
customer.add(customers);
System.out.println("new customer " + customers.getName() + " added");
}
// **
public void deleteCustomer(String name, int id) {
Customer customers = new Customer(id, name);
if (customer.contains(name)) {
customer.remove(name);
}
System.out.println("Customer " + customers.getName() + " deleted");
}
public Customer findCustomer(int id) {
for (Customer c : customer) {
if (c.getId() == id) {
return c;
}
}
return null;
}
public void addHotel() {
Hotel H1 = new Hotel();
Scanner name = new Scanner(System.in);
System.out.println("Please Enter the name of Hotel: ");
String n1 = name.nextLine();
bookable.add(H1);
System.out.println("The Hotel " + name + "added");
}
public void makeABooking(Customer c, Bookable b) {
Scanner input =new Scanner(System.in);
System.out.println("Please Enter your name: ");
String name = input.nextLine();
System.out.println("Please Enter your ID: ");
int ID = input.nextInt();
while(true) {
if(ID == -1 && ID == 0) {
System.out.println("Invalid ID. Enter again: ");
name = input.nextLine();
System.out.println("Please Enter your ID: ");
ID = input.nextInt();
}
}
}
}
(Your question is more suitable to https://softwareengineering.stackexchange.com/ - recommend asking it there...)
General speaking it wouldn't make sense to have a Hotel without a name, location or number of rooms so I'd recommend adding a constructor with minimal required information:
public Hotel (String name, String location, int rooms) {
this.name = name;
this.location = location;
this.noOfRooms = rooms;
}
bookingDate makes no sense as a single property of a hotel but rather a property of each booked room so you have a design issue - this is not addressed here.
Again, roomPrice usually varies by room so in a robust solution this would be a property of a room not a hotel - not addressed here.
Why is there a noOfRooms and a numberOfRooms list. In fact, the numberOfRooms list doesn't make sense as a list. I'd just keep the noOfRooms and get rid of numberOfRooms.
An implied property, nbrOfAvailableRooms can be derived from noOfRooms - bookedRooms.size();
I would assume your bookedRooms is a list of room numbers which are booked but that's not possible to tell from your implementation. You should focus on what you want Book to do.
The Book interface method is not documented but it looks like it should simply take an available asset (room) and consider it booked. It should return a boolean success not a String - especially not null.
I recommend writing (in pseudo code) what you want a Book implementation to do - include that in question. That is the core issue you are having.

Finding Percentages of elements inside an ArrayList<model>

So I am doing a project which I want to built a library with two ArrayLists one of the ArrayList'<'Book'>' BookList contains an element named quantity has to greater or equivalent to zero if the quantity of the book is above zero another element called status in the BookList is set to In-stock if it's equal to zero it's set to borrowed. I'm trying to create a method that looks at the BookList and shows the percentage of books that are borrowed. I have done this by going through the list and each time it finds a book with quantity below 1 in other words 0 the counter goes up by one so in the end I just substract the counter from the BookList.size(), divide the result with the BookList.size(), multiply it by 100 and fially print it.
Main Class
public class Main {
public static void main(String[] args) {
Scanner keyb = new Scanner(System.in);
int uinput;
Library nag;
try{
nag = new Library();
do{
System.out.println("Type 1 to add a book.");
System.out.println("Type 2 to show how many books are borrowed.");
uinput = keyb.nextInt();
if (uinput==1){
nag.addBook();
}
if (uinput==2){
nag.statistics();
}
}while (uinput > 0);
}
catch(Exception e){
System.out.println("Invalid entry.");
}
}//end of main
}//end of class
Book Class
public class Book {
private String Title;
private String Author;
private String ISBN;
private String Publisher;
private String Publication_Date;
private String Price;
private int Quantity;
private String Status;
public Book(){
Title= "";
Author="";
ISBN="";
Publisher="";
Publication_Date="";
Price="";
Quantity=1;
Status="IN-STOCK";
}
//getters
public String gettitle(){return Title;}
public String getauthor(){return Author;}
public String getisbn(){return ISBN;}
public String getpublisher(){return Publisher;}
public String getpublication_date(){return Publication_Date;}
public String getprice(){return Price;}
public int getquantity(){return Quantity;}
public String getstatus(){return Status;}
//setters
public void settitle(String t){Title = t;}
public void setauthor(String a){Author = a;}
public void setisbn(String is){ISBN = is;}
public void setpublisher(String p){Publisher = p;}
public void setpublication_date(String pd){Publication_Date = pd;}
public void setprice(String pr){Price = pr;}
public void setquantity(int q){Quantity = q;}
public void setstatus(String s){Status = s;}
}//end of class
Library Class
public class Library {
private ArrayList<Book> BookList;
public Library(){
BookList = new ArrayList<Book>();
}//end of constructor 1
public Library(ArrayList<Book> l) {
BookList = l;
}//end of constructor 3
public void addBook(){
try{
Scanner keyb = new Scanner(System.in);
Book bo = new Book();
System.out.println("Type the title: ");
String title_input;
title_input = keyb.nextLine();
bo.settitle(title_input);
System.out.println("Type the author: ");
String author_input;
author_input = keyb.nextLine();
bo.setauthor(author_input);
System.out.println("Type the isbn: ");
String isbn_input;
isbn_input = keyb.nextLine();
bo.setisbn(isbn_input);
System.out.println("Type the publisher: ");
String publisher_input;
publisher_input = keyb.nextLine();
bo.setpublisher(publisher_input);
System.out.println("Type the publication date: ");
String publication_date_input;
publication_date_input = keyb.nextLine();
bo.setpublication_date(publication_date_input);
System.out.println("Type the price: ");
String price_input;
price_input = keyb.nextLine();
bo.setprice(price_input);
System.out.println("Type the quantity: ");
int quantity_input = Integer.parseInt(keyb.nextLine());
if (quantity_input >= 0){
bo.setquantity(quantity_input);
if (quantity_input > 0){
bo.setstatus("IN_STOCK");
}
if(quantity_input == 0){
bo.setstatus("BORROWED");
}
BookList.add(bo);
System.out.println("Book added successfully.");
}
}catch(Exception e){
System.out.println("Invalid entry");
}//end of addBook()
public void statistics(){
Book bo = new Book();
int counter = 0;
for(int i=0; i < BookList.size();i++){
bo= BookList.get(i);
int holdquantity = bo.getquantity();
if (holdquantity < 1){
counter++;
}
}
double substraction=BookList.size() - counter;
double division= substraction/BookList.size();
double percentage = division * 100;
System.out.print(percentage + "%");
}//end of statistics()
}//end of class
The problem is that it keeps printing 100.0% when I have a book with quantity of zero and another book with quantity above zero.
So I wanted to know if the problem lies within this code or elsewhere.
Let's say your Book class is as follows:
package com.company;
public class Book {
private int quantity;
public Book(int quantity) {
this.quantity = quantity;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
And your Main is as follows:
package com.company;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main (String[]args) {
List<Book> bookList = new ArrayList<>(){{
add(new Book(4));
add(new Book(0));
add(new Book(3));
add(new Book(7));
add(new Book(0));
add(new Book(0));
add(new Book(1));
add(new Book(9));
add(new Book(0));
add(new Book(5));
}};
int booksOutOfStock = 0;
for (int i = 0; i < bookList.size(); i++) {
if (bookList.get(i).getQuantity() == 0)
booksOutOfStock++;
}
double percentage = 100d / bookList.size() * booksOutOfStock;
System.out.printf("Out of total %d books, %d are out of stock, which makes %.2f%%", bookList.size(), booksOutOfStock,
percentage);
}
}
So check this code, compare it to yours and see where could the error be, or post complete code here so we can help more.
Output of code above:
Out of total 10 books, 4 are out of stock, which makes 40.00%
OK, so after you posted your code I reviewed it, and apart from doing some things the hard way, your code is "working", all I had to do was add a closing brace in Library class at the end of addBook() method after catch block:
catch(Exception e){
System.out.println("Invalid entry");
} --> } <--- (added)
//end of addBook()
And I fixed your percentage code logic, you code would print out the number of non borrowed books as borrowed percentage, here is that code changed:
double division= (double)counter/BookList.size();
double percentage = division * 100;
System.out.printf("%.2f", percentage);

Java - One parseInt shows error, the other one doesn't

I've been doing my homework, but I ran into a problem. My code scans some information about books (author, title etc..) from a txt file then prints it. First I tried to print the author, title, ISBN code, the number of the pages, then the price of the books which is 15*number of pages. It works so far, however I wanted to add a number for each book, so it goes like a list. But when I modified the code to add those numbers, the code didn't want to scan them. it says
int cannot be converted to String
I tried to scan the numbers as Strings out of curiosity, but then the error message said that
String cannot be converted to int
My Book class:
public class Book {
private int number;
private String author;
private String title;
private String code;
private int pages;
private static int multiplier = 15;
public Book(String author, String title, String code, int pages, int number) {
this.number = number;
this.author = author;
this.title = title;
this.code = code;
this.pages = pages;
}
#Override
public String toString() {
return author + " - " + title + ", ISBN:" + code + ", " + pages + " pages, Price: " + price() + "Ft";
}
public int price() {
return multiplier * pages;
}
public static int getMultiplier() {
return multiplier;
}
public static void setMultiplier(int multiplier) {
Book.multiplier = multiplier;
}
public int getNumber() {
return number;
}
public String getAuthor() {
return author;
}
public String getTitle() {
return title;
}
public String getCode() {
return code;
}
public int getPages() {
return pages;
}
}
And my "Controller" class:
public class Controller {
void start() {
scanning();
printing("Avilable books: ");
}
private List<Book> books = new ArrayList<>();
private void scanning() {
try {
Scanner fajlScanner = new Scanner(new File("books.txt"));
String row;
String data[];
while (fajlScanner.hasNextLine()) {
row = fajlScanner.nextLine();
data = row.split(";");
//1;J.K. Rowling;Harry Potter and the Philosopher's Stone;1782637594826;342
//this line below gives the error for the data[0]
books.add(new Book(Integer.parseInt(data[0]), data[1], data[2], data[3], Integer.parseInt(data[4])));
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void printing(String title) {
System.out.println(title);
for (Book book : books) {
System.out.println(book);
}
}
}
The content of my txt:
1;J.K. Rowling;Harry Potter and the Philosopher's Stone;1782637594826;342
2;J.R.R. Tolkien;The Fellowship of the Ring;1827493762573;431
3;Stephen King;Needful Things;8274653821647;411
4;Eric Knight;Lassie Come-Home;7263845618293;138
5;Molnár Ferenc;A pál utcai fiúk;9283746192846;194
6;Winston Groom;Forrest Gump;0385231342;228
7;Antoine de Saint-Exupéry;The Little Prince;8362748172649;69
8;Stephen King;Cujo;2918467382914;362
I can scan the pages good, but it has some problem with the "number".
Check that you are giving the right parameters in the right order to your Book-constructor.
The constructor:
public Book(String author, String title, String code, int pages, int number)
Your object creation:
new Book(Integer.parseInt(data[0]), data[1], data[2], data[3], Integer.parseInt(data[4]))
Can you spot the error?
your input is: 1;J.K. Rowling;Harry Potter and the Philosopher's Stone;1782637594826;342
your constructor is:
public Book(String author, String title, String code, int pages, int number){
/*.
.
.*/
}
first character of input is "1" which is an integer but in your constructor the first parameter is a String. that's why the error showed up. "1" must be at the end of the input according to the constructor.
for set a number for each book, use a additional static variable, initialize it to 1, every time you wanna add a book, set the current value of the static variable for the book's number, then ++ it.
public class Book {
private static int counter=1;
private int number;
private String author;
private String title;
private String code;
private int pages;
private static int multiplier = 15;
public Book(String author, String title, String code, int pages, int number) {
this.number = counter;
this.author = author;
this.title = title;
this.code = code;
this.pages = pages;
counter++;
}
Good Luck

Calling method from an instance of a class

I'm new at java so sorry for the inconsistencies.
I'm creating a library program and I'm having trouble calling a method from the Book class in the Patron class.
In the Patron class I have a method checkOutBook() which a user can input a book to check out. However I'm having trouble accessing the setStatus() method in Book. I know I have to call it against an instance of the Book class but I'm unsure how to do so with a user inputed string.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Book implements BookInterface {
Scanner input = new Scanner(System.in);
static ArrayList < String > UserList = new ArrayList < String > ();
static ArrayList < String > BookList = new ArrayList < String > ();
public String title;
public String author;
public Book book;
private String status;
private String borrower;
public Book(String t, String a) {
title = t;
author = a;
}
//constructor create new book
public Book(String newTitle) {
title = newTitle;
}
public String toString() {
return title + " " + author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getStatus(String book) {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public void setBorrower(String borrower) {
this.borrower = borrower;
}
public String getBorrower(String checkPatron) {
return borrower;
}
public String getBook(String checkPatron) {
return book;
}
public void setBook(Book bookCheckOut) {
this.book = bookCheckOut;
}
}
public void CheckOutBook() {
Scanner inputread = new Scanner(System.in);
Scanner input = new Scanner(System.in);
System.out.println("Enter full patron name: ");
String borrower = inputread.nextLine();
System.out.println("Enter book title to check out: ");
String bookCheckOut = inputread.nextLine();
if (Book.BookList.contains(bookCheckOut)) {
Book.BookList.remove(bookCheckOut);
Book.setStatus("OUT"); //error message
Book.setBorrower(borrower); //error message
System.out.println("----------" + bookCheckOut + " has been checked out!----------");
System.out.println("-------------------BOOK STATUS:---------------------");
System.out.println("Book Title: " + bookCheckOut);
System.out.println("Book Status: Checked out");
System.out.println("Borrower: " + borrower);
System.out.println("Due Date: " + dueDate);
System.out.println("----------------------------------------------------");
I attempted to do this but it didn't work either :(
Thank you for your help!
Book bookCheckOut = new Book(bookCheckOut); //error: constructor Book(book) undefined
bookCheckOut.setStatus("OUT");
bookCheckOut.setBorrower(borrower);
bookCheckOut.setBook(bookCheckOut);
Book bookCheckOut = new Book(bookCheckOut); <~ I think you are getting confused because you already defined bookCheckOut as a String from the scanner and in this line you are setting it to a book object. Try changing the first bookCheckOut in this line to something else. Syntax: Book bookObjectName = new Book("String");
For the setStatus and setBorrower error you are trying to use those methods as if they were static. To fix this don't call Book.setStatus but replace Book with your instantiated book object name. Example: Book b = new Book ("Asd","abc"); b.setStatus("xyz");
Also, why do have two scanners?
Change Book.BookList from ArrayList<String> to Map<String, Book> as shown below:
public class Book {
static Map<String, Book> BookList = new HashMap<>();
...
Then in CheckOutBook() change:
if (Book.BookList.contains(bookCheckOut)) {
Book.BookList.remove(bookCheckOut);
Book.setStatus("OUT"); //error message
Book.setBorrower(borrower); //error message
...
To:
Book book = Book.BookList.get(bookCheckOut);
if (book != null) {
Book.BookList.remove(bookCheckOut);
book.setStatus("OUT");
book.setBorrower(borrower);
...

Categories

Resources