So this is a rough work in progress. I am making a text based information kiosk where people can do a search by author, title, etc. Right now I am having a hard time adding book using the kiosk. I can add all the info, but after I enter the information per book, I get a No Such Element exception. No sure what that means and any help would be appreciated.
import java.util.Scanner;
import java.util.ArrayList;
public class Books{
public static void main(String[] args) {
//Part 1: Initialize the MIS
//Part 1.1: Open Scanner
Scanner keyboard = new Scanner(System.in);
//Part 1.2: Build a store
Store newstore = new Store();
//Part 1.3: Build an array of books
final int MAX_NUM_BOOKS = 500;
Books[] list_book = new Books[MAX_NUM_BOOKS];
//Part 1.4: Prompt for the initial book count
System.out.println("How many books do we have?");
int bookcount = keyboard.nextInt();
//Part 1.5: Builds the books
for(int i=0; i<bookcount; i++) list_book[i] = new Books();
//Part 1.6: Create switch menu
boolean exit = false;
while(!exit){
System.out.println("Please make a selection: ");
System.out.println("To search by Title (0)");
System.out.println("To search by Author's Last name (1)");
System.out.println("To search by Author's First name (2)");
System.out.println("To search by ISBN (3)");
System.out.println("To add a book to the inventory (4)");
System.out.println("To exit (5)");
int option = keyboard.nextInt();
switch(option){
case 0:System.out.print("Please enter the title of the book you are looking for: ");
String title = keyboard.next();
results(Book.TitleSearch(title));
break;
case 1: System.out.print("Please enter the last name of the author you are looking for: ");
String auth_last = keyboard.next();
results(Book.Auth_LastSearch(auth_last));
break;
case 2:System.out.print("Please enter the first name of the author you are looking for: ");
String auth_first = keyboard.next();
results(Book.Auth_FirstSearch(auth_first));
break;
case 3:System.out.print("Please enter the ISBN of the book you are looking for: ");
String ISBN = keyboard.next();
results(Book.ISBNSearch(ISBN));
break;
case 4:addBook(newstore);
break;
case 5: exit=true;
}//switch
}//while
//Part :Close Input
keyboard.close();
}
//Part 2: Add Books to the Store
private static void addBook(Store newstore) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter title of the book: ");
String title = keyboard.next();
System.out.print("Enter Author's first name: ");
String auth_first_nam = keyboard.next();
System.out.print("Enter Author's last name: ");
String auth_last_nam = keyboard.next();
System.out.print("Enter the ISBN: ");
String isbn = keyboard.next();
Book book = new Book(title, auth_first_nam, auth_last_nam, isbn);
Store.addBook(book);
keyboard.close();
}
private static String results(String titleSearch) {
return Book.output();
}
}
//Build each individual book
class Book{
private static String title;
private static String auth_first_nam;
private static String auth_last_nam;
private static String isbn;
private static String bookinfo;
public Book(Scanner keyboard){
System.out.println("Enter the book Title: ");
title=keyboard.next();
System.out.println("Enter in the Author's Last Name: ");
auth_last_nam=keyboard.next();
System.out.println("Enter in the Author's First Name: ");
auth_first_nam=keyboard.next();
System.out.println("Enter the ISBN number: ");
isbn=keyboard.next();
}
public Book(String title, String auth_first_nam, String auth_last_nam, String isbn) {
}
public static String output() {
bookinfo=(title+" by " + auth_first_nam + " " + auth_last_nam + ". ISBN: " +isbn);
return bookinfo;
}
public static String ISBNSearch(String iSBN2) {
return isbn;
}
public static String Auth_FirstSearch(String auth_first) {
return auth_first_nam;
}
public static String Auth_LastSearch(String auth_last) {
return auth_last_nam;
}
public static String TitleSearch(String title2) {
return title;
}
public String getTitle() {
return title;
}
public String GetAuthorLast(){
return auth_last_nam;
}
public String GetAuthorFirst(){
return auth_last_nam;
}
public String getISBN() {
return isbn;
}
}
class Store{
private static ArrayList<Book> books;
private static Book book;
public Store(){
books = new ArrayList<Book>();
}
public static void addBook(Book Book){
if(book==null){
System.out.println("I'm sorry, but you didn't enter in any information.");
return;
}
else{
books.add(Book);
}
}
public Book getTitle(String title){
for(int i=0;i<books.size(); i++)
{
if(books.get(i).getTitle().equals(title))
{
book=books.get(i);
}
}
return book;
}
public ArrayList<Book> findAutLast(String aut_last_nam)
{
ArrayList<Book> found = new ArrayList<Book>();
for(int i=0; i<books.size(); i++)
{
Book current = books.get(i);
if(current.GetAuthorLast().indexOf(aut_last_nam) >=0)
{
found.add(current);
}
}
return found;
}
public ArrayList<Book> findTitle(String title){
ArrayList<Book> found = new ArrayList<Book>();
for(int i=0; i<books.size();i++)
{
Book current = books.get(i);
if (current.getTitle().indexOf(title) >=0)
{
found.add(current);
}
}
return found;
}
public ArrayList<Book> findISBN(String isbn)
{
ArrayList<Book> found = new ArrayList<Book>();
for(int i=0; i<books.size(); i++)
{
Book current = books.get(i);
if(current.getISBN().indexOf(isbn) >=0)
{
found.add(current);
}
}
return found;
}
}
Sorry, there's some dead code and loose ends still being tied up. Just really curious about the No Element as I've never seen it before. It happens at line 35 after using the Switch for case 4.
The issue is actually in this method:
private static void addBook(Store newstore) {
...
keyboard.close();
}
Where you close the keyboard instance of a Scanner.
The loop in which you call addBook is making use of the keyboard scanner, and the next time through the loop calls keyboard.nextInt() fails, because the scanner is closed.
I deduced this by running your code, and observing the following exception:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at Books.main(Books.java:36)
Notably, line 36 is
int option = keyboard.nextInt();
And I only hit this exception after running option 4 (add a book).
If you remove keyboard.close() from your addBook() method, your program will no longer crash.
I don't expect your program to work, as you have a number of other errors (misuse of static fields and methods), but it will no longer throw a NoSuchElementException.
As a hint (since this appears to be homework), the other problems I'm seeing in your program:
static fields for Book (so the properties you wish to define on a book won't persist with the object)
static method son Book (similar to above)
failure to set fields in Book using the appropriate constructor (and repeating code from addBook in an inappropriate constructor)
Creating a Books[] instead of what you likely want, which is a Book[] (or maybe this is irrelvant since you have an ArrayList<Book> books in Store
Though it's really hard to tell because you haven't provided the stacktrace, I could see a problem arrising when to access an element in the ArrayList. It's hard to tell just by staring at your code, but I would start by fixing this
private static String title;
private static String auth_first_nam;
private static String auth_last_nam;
private static String isbn;
private static String bookinfo;
All of these fields you have as static. That means that for every Book you create and add the ArrayList of books, every single one will have the exact same title, auth_first_nan, auth_last_nam, isbn, and bookinfo. That could cause a problem in the program. Though probably doesn't cause the NoSuchElementException, I would still make this fix.
For example, if you first add a Book with title "StackOverflow", then you add a Book with title "StackExchange", the first Book's title also become "StackExchange". That means that if you ever try and access a Book by title "StackOverflow", you would never find it
Change all the fields to not include the static
private String title;
private String auth_first_nam;
private String auth_last_nam;
private String isbn;
private String bookinfo;
Check out Java tutorial for static keyword
Related
I am new to OOP and Java Classes, so bear with me.
I am trying to create a class that allows me to store data about books, specifically the fields: Title, Author, Year published, Page count, Genre
Then with that class, I wish to have a main program that runs, asks for a number of books to enter and then allows the user to input the information for each book. Then, a summary is printed for each book.
I have attempted to program a class "bookClass" that allows input of the book information and then a class "bookTest" that creates an array using the bookClass.
This is the bookClass:
public class bookClass {
private String title;
private String author;
private String year;
private String pageCount;
private String genre;
private static int bookCount;
public bookClass(String title, String author, String year, String pageCount, String genre) {
this.setTitle(title);
this.setAuthor(author);
this.setYear(year);
this.setPageCount(pageCount);
this.setGenre(genre);
bookCount++;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthor(String author) {
this.author = author;
}
public void setYear(String year) {
this.year = year;
}
public void setPageCount(String pageCount) {
this.pageCount = pageCount;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getYear() {
return year;
}
public String getPageCount() {
return pageCount;
}
public String getGenre() {
return genre;
}
public int getBookCount() {
return bookCount
}
}
This is the main class:
import java.util.*;
public class bookTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.print("How many books would you like to enter: ");
int bookAmount = input.nextInt(); input.nextLine();
String[][] books2DArray = new String[bookAmount][5];
for (String[] books1DArray: books2DArray) {
System.out.print("Please enter the title: ");
String title = input.nextLine();
System.out.print("Please enter the author ");
String author = input.nextLine();
System.out.print("Please enter the year: ");
String year = input.nextLine();
System.out.print("Please enter the page count: ");
String pageCount = input.nextLine();
System.out.print("Please enter the genre: ");
String genre = input.nextLine();
bookClass book = new bookClass(title, author, year, pageCount, genre);
books1DArray[0] = book.getTitle();
books1DArray[1] = book.getAuthor();
books1DArray[2] = book.getYear();
books1DArray[3] = book.getPageCount();
books1DArray[4] = book.getGenre();
}
for (String[] books1DArray: books2DArray) {
printSummary( books1DArray[0], books1DArray[1], books1DArray[2], books1DArray[3], books1DArray[4]);
}
System.out.println("There are" + book.getBookCount() + "books in the system");
}
public static void printSummary(String title, String author, String year, String pageCount, String genre) {
System.out.format("%s written by %s was published in %s, has %s pages and is of the %s genre", title, author, year, pageCount, genre);
}
}
I have multiple issues/questions:
Would it be better to create the array in the main class?
I feel like I am being highly inefficient as it feels like I am repeating myself in the code over and over. Some of the redundancy is necessary for good practice (such as getters and setters), but am I overdoing it?
In the for loop in the main class, I want to create multiple objects and add them to the array, but I am unsure how to do that as it would require different names to avoid being overwritten.
Also, calling getBookCount at the end of my main class does not work. Is there a reason for this?
I would appreciate any general advice or other things you may notice, as I feel as though I am fundamentally misunderstanding the use of Java classes.
You are learning Java, so you should learn Java name conventions.
I assume your book class public class BookClass, you can write your test class that uses 1 array of BookClass (or ArrayList or any collection type you want), for example (Skip input checking)
public class BookTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many books would you like to enter: ");
int bookAmount = input.nextInt(); input.nextLine();
BookClass[] books = new BookClass[bookAmount];
for (int i = 0; i < bookAmount; i++) {
System.out.print("Please enter the title: ");
String title = input.nextLine();
System.out.print("Please enter the author ");
String author = input.nextLine();
System.out.print("Please enter the year: ");
String year = input.nextLine();
System.out.print("Please enter the page count: ");
String pageCount = input.nextLine();
System.out.print("Please enter the genre: ");
String genre = input.nextLine();
books[i] = new BookClass(title, author, year, pageCount, genre);
}
for (BookClass book : books) {
printSummary(book.getTitle(), book.getAuthor(), book.getYear(), book.getPageCount(), book.getGenre());
}
System.out.println("There are" + books.length + "books in the system");
}
public static void printSummary(String title, String author, String year, String pageCount, String genre) {
System.out.format("%s written by %s was published in %s, has %s pages and is of the %s genre", title, author, year, pageCount, genre);
}
}
You don't need static attribute in BookClass to store the number of books, you have many ways to do it.
Your getBookCount does not work because you call an undefined parameter book which you defined in side for loop. If you want, you should define a static getter method public static int getBookCount(), and access it BookClass.getBookCount(). But I advice you to do not use it to count object, because it can make wrong in complicated program when you remove object, use multi-threading with out synchronization ...
I am working on a Library system project for my Java programming class. I need to be able to search through the list of books in the Book array by author or title. In addition, I would also like to see how to check out books in the system. I would appreciate any help or insight. The searchBooks and checkoutBook methods are at the bottom. Thanks again!
Sincerely,
Moon
package Project;
import java.util.ArrayList;
import java.util.Scanner;
public class Library {
static Scanner input = new Scanner(System.in);
ArrayList<Book> booklist = new ArrayList<Book>();
ArrayList<Users> user = new ArrayList<Users>();
static int running = 0;
String booksearch;
public static void main(String[] args) {
(new Library()).run();
}
public void run() {
while(true){
System.out.println("********************Welcome to the Public Library!********************");
System.out.println(" Please Select From The Following Options: ");
System.out.println("**********************************************************************");
System.out.println("1: Create a new account");
System.out.println("2: Admin login");
System.out.println("3: User login");
System.out.println("0: Exit");
int option = input.nextInt();
switch (option) {
case 1: newAccount(); break;
case 2: admin(); break;
case 3: userLogin(); break;
case 0: System.exit(option); break;
case 5: return;
default: System.out.println("Wrong option, try again.");
}
}
}
public void addBook(){
Book book1 = new Book("Game of Thrones","Fantasy","George RR Martin","a book about dragons",9001,5);
Book book2 = new Book("Harry Potter","Adventure","JK Rowling","a boy goes to a magical school",23454,3);
Book book3 = new Book("Carrie","Horror","Stephen King","a girl goes crazy",3332,15);
Book book4 = new Book("Dragonaball","Action Manga","Akira Toriyama","a boy with power fights evil",27894,2);
booklist.add(book1);
booklist.add(book2);
booklist.add(book3);
booklist.add(book4);
}
private void userLogin() {
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter your username ");
String user = keyboard.nextLine();
System.out.println("Enter your password ");
String pass = keyboard.nextLine(); // looks at selected file in scan
if (user.equals("olumide1") && pass.equals("umbc")) {
System.out.println("********************Welcome Home, User!********************");
System.out.println(" Please Select From The Following Options: ");
System.out.println("**********************************************************************");
System.out.println("1: checkout a book:");
System.out.println("2: search a book:");
System.out.println("3: exit library:");
int option = input.nextInt();
switch(option){
case 1: checkOutBook(); break;
case 2: searchBooks(); break;
case 3: System.exit(0);
}
} else {
System.out.print("Try again");
}
}
public void searchBooks() {
System.out.println("Which book are you searching for today?");
booksearch = input.nextLine();
}
private void checkOutBook() {
}
To search a Book, simply iterate through your bookList and search by title or author. Also, I suggest that your searchBooks() method should return a Book instance:
public Book searchBooks() {
System.out.println("Which book are you searching for today?");
booksearch = input.nextLine();
for (Book book : booklist)
{
if (book.getTitle().contains(booksearch) || book.getAuthor().contains(booksearch)
{
return book;
}
}
return null; //no book was found
}
To track checked out / free books, simply create a new List of books that are checked out checkedOutBooks. You checkOutBook method should accept Book argument:
private void checkOutBook(Book book) {
checkedOutBooks.add(book);
}
for search book method you can use hashmap, google and spend some time on it. Please provide detail for checkoutbook, what needs to be done in it.
Create 2 Pojo's
Class Book
{
int id;
int quantity;
String bookName;
Author author;
}
Class Author
{
int authorId;
String authorName;
List<Integer>bookIdsList;
}
Intialize the class with 3 Maps
TreeMap<String,Integer>bookSearchMap //String is the bookName // Integer is the book Id
TreeMap<String,Author>authorSearchMap //String is the authorName
HashMap<Integer,Book>bookData // for checking out the book with the Id of book
so the 2 TreeMap will help you in searching
and HashMap will help you in checking out .
If you want a prefix search you can use TRIE structure but that you will have to implement .
Could you please help me figure out why when i add a new book it overwrites all of the books with the current one? ---------------------- |Name| -|ISBN|-|Author|
for example i add a book called |game| | of | Thrones|
and if i go & add a book named |Song| | of | Ice and fire |
no matter if there are 10 books there they will all be renamed according to the last entry
(here Song of ice and fire)
//Package ask1 main class Library
package ask1;
import java.lang.Object.*;
import java.util.Scanner;
import java.util.Arrays;
import java.io.*;
public class library {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
Management manager = new Management();
Scanner input = new Scanner(System.in);
Book vivlio = new Book();
System.out.println("\n\t\t^*^*^*^*^*^*^* LIBRARY MANAGEMENT ^*^*^*^*^*^*^");
while (true) {
System.out.println("------------------MENU-------------------------------");
System.out.print("\nENTER UR CHOICE\n\t" +
"1:Add a new Book\n\t" +
"2:Edit Book Infos\n\t" +
"3:Search a Book (with ISBN)\n\t" +
"4:Show all the Books\n\t" +
"5:Delete a Book (with ISBN)\n\t" +
"6:Exit \n :");
int selection;
selection = input.nextInt();
if (selection == 1) {
System.out.println("Adding a new book ");
String empty = input.nextLine();
System.out.println("name of book:");
vivlio.name = input.nextLine();
System.out.println("Author:");
vivlio.author = input.nextLine();
System.out.println("ISBN:");
vivlio.isbn = input.nextLine();
System.out.println("Number of copies:");
vivlio.number = input.nextInt();
System.out.println("");
manager.AddBook(vivlio);
} else if (selection == 2) {
System.out.println("Editing a Book ");
System.out.println("Please enter title of book to edit:");
String title = input.next();
Book editingBook = findBookByTitle(title);
if (editingBook == null) {
System.out.println("Sorry no book found with title name = " + title);
} else {
//ask user for new price etc what ever you want to edit.
System.out.println("Please enter new values:");
String newValue = input.nextLine();
editingBook.setPrice(newValue);
// etc. other editing to book.
}
} else if (selection == 3) {
System.out.println("Searching a Book ");
} else if (selection == 4) {
System.out.println("You Choose to view all the Books ");
manager.PrintAllBooks();
} else if (selection == 5) {
System.out.println("You Choose to Delete a Book ");
String empty = input.nextLine();
} else if (selection == 6) {
System.out.println("Library System Terminated!!! ");
String empty = input.nextLine();
System.exit(0);
} else {
System.out.println("Wrong Choice");
}
}
}
private static Book findBookByTitle(String title) {
// TODO Auto-generated method stub
return null;
}
here is the second class called Book
package ask1;
import java.util.Scanner;
public class Book {
Scanner input = new Scanner(System.in);
public String isbn;
public String name;
public String author;
public int number;
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
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 getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
String bookinfo = name + " ," + author + " ," + isbn;
public void setPrice(String newPrice) {
// TODO Auto-generated method stub
}
}
And the third class called Management
package ask1;
import java.util.Scanner;
public class Management {
Scanner input = new Scanner( System.in );
private Book[] books =new Book [60];
private String isbns = new Book().isbn;
private String name = new Book().name;
int current = 0;
//Number 1
public void AddBook(Book vivlio)
{
books[current]=vivlio;
current++;
}
//Number 3
//Number 4
public void PrintAllBooks()
{
for (int i=0;i<current;i++)
{
Book b = books[i];
System.out.println(b.name);
}
}
}
return searchBook;
}
}
The problem is that vivlio always means the same book. You only create one Book object, here:
Book vivlio = new Book();
and proceed to add it to the list several times, while changing its name each time. However, since it's just one book that happens to be on the list several times, when you change one you change all.
You can make it better by simply changing the scope. Move the creation of the book inside the loop:
while(true) {
Book vivlio = new Book();
...
Now vivlio is initialized to a different book each time, instead of using the same book all the time.
Your problem: You create Book vivlio = new Book(); once and re-use it every time. So whenever you set a parameter, you set it for this one book and therefore overwrite what you did before.
The easiest solution is to move
Book vivlio = new Book();
into your while loop.
That will create a new Book object each time you run through the loop.
By the way, there would be some ways to improve the code. For example, don't reference another object's attribute directly, but use getter and setter methods. Also, it is pretty standard to start function names with lower case chars.
Book object is created only once and after calling the following method.
public void AddBook(Book vivlio) {
books[current] = vivlio;
current++;
}
You are just assigning the same object object to array.
That means you are changing the values inside vivlio again and again but referencing the same object in array to different places thats why you are getting the same output in all the books.
Here is the right code for your reference.
public class library {
public static void main(String[] args) throws InstantiationException,
IllegalAccessException {
Management manager = new Management();
Scanner input = new Scanner(System.in);
System.out
.println("\n\t\t^*^*^*^*^*^*^* LIBRARY MANAGEMENT ^*^*^*^*^*^*^");
while (true) {
Book vivlio = new Book();
System.out
.println("------------------MENU-------------------------------");
System.out
.print("\nENTER UR CHOICE\n\t1:Add a new Book\n \t2:Edit Book Infos\n\t3:Search a Book (with ISBN)\n\t4:Show all the Books\n\t5:Delete a Book (with ISBN)\n\t6:Exit \n :");
int selection;
selection = input.nextInt();
if (selection == 1) {
System.out.println("Adding a new book ");
String empty = input.nextLine();
System.out.println("name of book:");
vivlio.name = input.nextLine();
System.out.println("Author:");
vivlio.author = input.nextLine();
System.out.println("ISBN:");
vivlio.isbn = input.nextLine();
System.out.println("Number of copies:");
vivlio.number = input.nextInt();
System.out.println("");
manager.AddBook(vivlio);
}
else if (selection == 2) {
System.out.println("Editing a Book ");
System.out.println("Please enter title of book to edit:");
String title = input.next();
Book editingBook = findBookByTitle(title);
if (editingBook == null) {
System.out.println("Sorry no book found with title name = "
+ title);
} else {
// ask user for new price etc what ever you want to edit.
System.out.println("Please enter new values:");
String newValue = input.nextLine();
editingBook.setPrice(newValue);
// etc. other editing to book.
}
}
else if (selection == 3) {
System.out.println("Searching a Book ");
} else if (selection == 4) {
System.out.println("You Choose to view all the Books ");
manager.PrintAllBooks();
} else if (selection == 5) {
System.out.println("You Choose to Delete a Book ");
String empty = input.nextLine();
} else if (selection == 6) {
System.out.println("Library System Terminated!!! ");
String empty = input.nextLine();
System.exit(0);
} else {
System.out.println("Wrong Choice");
}
}
}
private static Book findBookByTitle(String title) {
// TODO Auto-generated method stub
return null;
}
}
Hope this might solve your problem.
Every time i pass an object to my array, it overwrites the previous entry. Can anybody spot why this is happening?
addbook() - when i put in name, and author it assigns a value , but when enter another title and author, it overwrites the previous entry.
public class library {
static Scanner keyboard = new Scanner(System.in);
static int count = 0;
public static void main(String [] args){
addBook();
} // Main end
static void addBook(){
loanbook [] loanArray = new loanbook[5];
String title,author;
int choice;
boolean onLoan;
loanbook book1; // TESTING ONLY
for(int x = 0; x < 5; x++){
System.out.print("Press 1 for Fiction or 2 for Non Fiction: "); // sub menu for fiction and non fiction
choice = keyboard.nextInt();
if (choice == 1){
System.out.println("Please enter book title: ");
title = keyboard.nextLine();
title = keyboard.nextLine();
System.out.println("Please enter book author: ");
author = keyboard.nextLine();
onLoan = false; // not used yet
book1 = new fiction(title,author);
System.out.println(book1.toString());
loanArray[x] = new loanbook(title,author);
}
else if (choice == 2) {
System.out.println("Please enter book title: ");
title = keyboard.nextLine();
title = keyboard.nextLine();
System.out.println("Please enter book author: ");
author = keyboard.nextLine();
onLoan = false; // not used yet
book1 = new nonfiction(title,author);
System.out.println(book1.toString());
loanArray[x] = new loanbook(title,author);
}
}
}
} // Library end
My Loanbook class
public class loanbook {
private String title,author;
private int bookID, count = 0;
public loanbook(String pTitle,String pAuthor){
bookID = count;
title = pTitle;
author = pAuthor;
count++;
} // Constructor
public void setTitle(String pTitle){
title = pTitle;
} // setTitle
protected String getTitle(){
return title;
} // getTitle
protected String getAuthor(){
return author;
} // getAuthor
public String toString(){
return " BookID: "+ bookID+"\n" + " Title: "+ getTitle()+"\n" +" Author : "+ getAuthor()+ "\n";
}
} // loanbook
You may want to make count static. I'm assuming you want the count to go up every time a new book is created. Without the static, the count value will not persist ever time a book is created, so your bookID will always be 0 for every book. That may be why you think "it's getting overwriten". I'm not totally sure because you haven't really explained what that means.
private int bookID;
public static int count = 0; <-- static
public loanbook(String pTitle,String pAuthor){
bookID = count;
title = pTitle;
author = pAuthor;
count++;
}
Or better yet, just avoid the count variable. You do the same as you would with the count. So count is unnecessary.
public static int bookID 0;
public loanbook(String pTitle,String pAuthor){
title = pTitle;
author = pAuthor;
bookId++;
}
Also, I don't know what you're planning to with loanbook book1;, but it is used every time in the loop, so I could see this being the possible "it is getting overwritten" problem. Assuming fiction and nonfiction extend loanbook
Also I don't see a need for the count in the library class. You can get rid of that.
Update:
Assuming you want the fiction or nonfiction book (and they both extend loanbook) in yourloanArray` may you want something like this
loanbook book = new fiction(title,author);
System.out.println(book1.toString());
loanArray[x] = book;
I am making a program for a library; the library contains different items such as book, videos, journals, ect...
I have a class called item with basic methods for every item in the library, and my classes for book, video, journal and all other items extend Item. I want to make an array to contain all of the items in the library so people can search for a specific item, it will find it in the array and display the info for that item.
The problem I'm having is that when I create an array of type Item I can only call methods of the Item class and I can't call the new methods I made for book in the book class or for journal in the journal class.
So I'm forced to have separate arrays for each of the different types of Items.
Is there a way to have just one array that can call methods from all the different classes for each item?
You can see my code below; I have only attached the code for my tester class where the array is, let me know if you need to see the code for the other classes. I would appreciate any help.
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 Video[] database2 = new Video[100];
static Journal[] database3 = new Journal[100];
static CD[] database4 = new CD[100];
static int count=0;
public static void main(String[] args){
int i;
Scanner s = new Scanner(System.in);
do{
System.out.println("type the adjacent number to preform that process.\n1: Add an item\n2: Checkout an item\n0: Exit program");
i=s.nextInt();
switch(i){
case 1:
addItem();
break;
case 2:
break;
}
}while(i != 0);
database[0].viewDetails();
database[1].viewDetails();
checkingOut();
database[0].viewDetails();
database[1].viewDetails();
}
public static void addItem(){
int i;
Scanner s = new Scanner(System.in);
do{
System.out.println("type the adjacent number to add the item.\n1: Book\n2: Video\n3: Journal\n4: CD\n Type 0 to stop");
i=s.nextInt();
switch(i){
case 1:
addBook();
break;
case 2:
addVideo();
break;
case 3:
addJournal();
break;
case 4:
addCD();
break;
}
}while(i != 0);
}
public static void addBook(){
String title;
String author;
int id;
int copies;
String date;
int count=0;
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 addJournal(){
String title;
String author;
int id;
int copies;
String date;
int count=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the title of the journal you want to add to the collection");
title=s.nextLine();
System.out.println("Enter the author of the journal you want to add to the collection");
author=s.nextLine();
System.out.println("Enter the publishing date of the journal you want to add to the collection");
date=s.nextLine();
System.out.println("Enter the ID number of the journal 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();
Journal Journal1 = new Journal(date, author, copies, id, title);
database3[count] = Journal1;
count++;
}
public static void addCD(){
String title;
String art;
String genre;
int id;
int copies;
int date;
int count=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the title of the cd you want to add to the collection");
title=s.nextLine();
System.out.println("Enter the artist of the cd you want to add to the collection");
art=s.nextLine();
System.out.println("Enter the release year of the cd you want to add to the collection");
date=s.nextInt();
System.out.println("Enter the genre of the cd you want to add to the collection");
genre=s.nextLine();
System.out.println("Enter the ID number of the cd 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();
CD CD1 = new CD(date, copies, id, title, art, genre);
database4[count] = CD1;
count++;
}
public static void addVideo(){
String title;
String director;
int id;
int copies;
int date;
String genre;
int count=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the title of the video you want to add to the collection");
title=s.nextLine();
System.out.println("Enter the director of the cd you want to add to the collection");
director=s.nextLine();
System.out.println("Enter the release year of the cd you want to add to the collection");
date=s.nextInt();
System.out.println("Enter the genre of the video you want to add to the collection");
genre=s.nextLine();
System.out.println("Enter the ID number of the video 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();
Video Video1 = new Video(date, copies, id, title, director, genre);
database2[count] = Video1;
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;
break;
}
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!");}
}
}
You could check the type and cast it to that type to gain access to the additional methods.
public static void main(String args[]){
for(Item item : itemList){
if(item instanceof Book){
Book book = (Book) item;
book.someBookMethod();
}
}
}
though using instanceof is considered harmful
A better design would be to make Item abstract and create the methods common to all children, such as add()
public abstract class Item{
public void add();
public void viewDetails();
}
class Book extends Item{
public void add(){
//fun stuff
}
public void viewDetails(){
//moar serious business logic
}
}
....
public static void main(String args[]){
for(Item item : itemList){
item.add();
}
}