I'm a beginner at Java so sorry for the mess ups.
Im creating a Library program and have 4 classes: Library, Book, BookInterface and Patron.
I'm in the last couple of stages of the program however I have error messages in the Library class as I'm having trouble with instances.
I got the error message "Cannot make a static reference to the non-static method" in ALL of my switch statements. I tried to create an instance of the Library class in case 1 but still an error message. Also I can't change those methods to static. Any help is much appreciated! :)
Library class:
import java.awt.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.Collections;
public class Library
{
public static void main(String[] args)
{
//create new library
Library newLibrary = new Library();
}
public Library()
{
Library library = new Library();
Scanner input = new Scanner(System.in);
int choice = 0;
System.out.println("********************Welcome to the Public Library!********************");
System.out.println(" Please Select From The Following Options: ");
System.out.println("**********************************************************************");
while(choice != 9)
{
System.out.println("1: Add new patron");
System.out.println("2: Add new book");
System.out.println("3: Edit patron");
System.out.println("4: Edit book");
System.out.println("5: Display all patrons");
System.out.println("6: Display all books");
System.out.println("7: Check out book");
System.out.println("8: Check in book");
System.out.println("9: Search book");
System.out.println("10: Search Patron");
System.out.println("11: Exit");
choice = input.nextInt();
switch(choice)
{
case 1: //Add new patron
//ERROR: Patron cannot be resolved or is not a field
library.Patron.newPatron();
break;
case 2: //Add new book
//ERROR: Cannot make a static reference to the non-static method
Book.addBook();
break;
case 3: //Edit patron name
Patron.editName();
break;
case 4: //edit book
//ERROR: Cannot make a static reference to the non-static method
Book.editBook();
break;
case 5: //display all patrons
System.out.println(Book.UserList);
break;
case 6: //display all books
//System.out.println(Book.OrigBookList);
Book.libraryInventory();
//Book.bookStatus()
break;
case 7: //check out a book
//ERROR: Cannot make a static reference to the non-static method
Patron.CheckOutBook();
break;
case 8: //check in a book
//ERROR: Cannot make a static reference to the non-static method
Patron.CheckInBook();
break;
case 9: //search book
//ERROR: Cannot make a static reference to the non-static method
Patron.bookStatus();
break;
case 10://search Patron
Patron.searchPatron();
break;
case 11: //exit program
}
}
}
}
Book class:
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
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> (); //display just titles// use when checking out books
static ArrayList <String> OrigBookList = new ArrayList <String> (); //keep track of all titles ever entered
public String title;
public String author;
public String book;
public boolean checkIn;
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 void addBook()
{
Scanner input = new Scanner(System.in);
Scanner inputread = new Scanner(System.in);
System.out.print("Enter book title: ");
String title1 = inputread.nextLine();
Scanner input1 = new Scanner(System.in);
System.out.print("Enter book author: ");
String author1 = inputread.next();
Book fullBook = new Book(title1, author1); //create constructor w/ title & author
Book book1 = new Book(title1); //constructor w/ just title to be used to display all books
//BookList.add(title1);
OrigBookList.add(title1);
setStatus("IN"); //false = checked in
System.out.println("-----------------------------------------------");
System.out.println("-----" + title1 + " is now in the library!-----");
System.out.println("-----------------------------------------------");
}
public void editBook()
{
Scanner inputread = new Scanner(System.in);
System.out.println("Enter original book title: ");
String origTitle = inputread.nextLine();
System.out.println("Enter edited book title: ");
String editedTitle = inputread.nextLine();
Collections.replaceAll(Book.UserList, origTitle, editedTitle);
System.out.println("------------------------------------------------------");
System.out.println(origTitle + " has been changed to " + editedTitle + "!");
System.out.println("------------------------------------------------------");
}
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(String bookCheckOut)
{
this.book = bookCheckOut;
}
public void libraryInventory()
{
System.out.println("------------------ Library Inventory: ---------------");
for(int i =0; i<= OrigBookList.size()-1; i++)
{
//Book Title: checked in/out
System.out.println(OrigBookList.get(i) + ":" + getStatus(OrigBookList.get(i)));
}
System.out.println("-----------------------------------------------------");
}
}
Patron class:
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Scanner;
public class Patron
{
Scanner input = new Scanner(System.in);
private String fullName;
int bookCount = 0; //amount books user has in pocket
int books = 0;
//constructor to "add new patron" by entering their name.
public Patron(String newName)
{
fullName = newName;
}
public String toString()
{
return fullName;
}
public String getName()
{
return fullName;
}
public void CheckOutBook()
{
//create and format due date (7days)
GregorianCalendar returnDate = new GregorianCalendar();
returnDate.add(GregorianCalendar.DATE, 7);
Date d = returnDate.getTime();
DateFormat df = DateFormat.getDateInstance();
String dueDate = df.format(d);
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();
Book checkOut = new Book(bookCheckOut);
if(Book.BookList.contains(bookCheckOut))
{
Book.BookList.remove(bookCheckOut);
checkOut.setStatus("OUT");
checkOut.setBorrower(borrower);
Book.BookList.remove(bookCheckOut);
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("----------------------------------------------------");
}
else if (!(Book.UserList.contains(borrower)))
{
System.out.println("Patron is not a part of library system. Please enter patron in system.");
}
else if (!(Book.BookList.contains(bookCheckOut)))
{
System.out.println(bookCheckOut + " is not in the library. Please enter "
+ "a different book to be checked out");
}
}
public void CheckInBook()
{
Scanner inputread = new Scanner(System.in);
System.out.println("Enter book title to be checked in: ");
String bookCheckIn = inputread.nextLine();
Book checkOut = new Book(bookCheckIn);
if((!Book.BookList.contains(bookCheckIn)) && Book.OrigBookList.contains(bookCheckIn))
{
Book.BookList.add(bookCheckIn);
checkOut.setStatus("IN");
System.out.println("------------------------------------------------------");
System.out.println("-----" + bookCheckIn + " has been checked in!-----");
System.out.println("------------------------------------------------------");
}
else
System.out.println(bookCheckIn + " is not part of the library system. Please enter "
+ "a different book to be checked in");
}
public boolean canBorrow()
{
if(bookCount <= 3)
{
return true;
}
else
{
return false;
}
}
public static void editName()
{
Scanner inputread = new Scanner(System.in);
System.out.println("Enter original patron full name: ");
String origName = inputread.nextLine();
System.out.println("Enter edited patron full name: ");
String editedName = inputread.nextLine();
Collections.replaceAll(Book.UserList, origName, editedName);
System.out.println("------------------------------------------------------");
System.out.println(origName + " has been changed to " + editedName + "!");
System.out.println("------------------------------------------------------");
}
public void newPatron()
{
Scanner inputread = new Scanner(System.in);
System.out.println("Enter patron full name: ");
String name = inputread.nextLine();
Book.UserList.add(name); //add name to userList
Patron patron1 = new Patron(name);
System.out.println("-----------------------------------------------------------------");
System.out.println("-----" + name + " has been added to the library system" + "-----");
System.out.println("-----------------------------------------------------------------");
}
public void bookStatus() //STOPS
{
Scanner input = new Scanner(System.in);
Scanner inputread = new Scanner(System.in);
System.out.println("Enter book title: ");
String checkStatus = inputread.nextLine();
Book status = new Book(checkStatus);
if(Book.OrigBookList.contains(checkStatus) && status.getStatus(checkStatus) == "OUT")
{
System.out.println("Status: checked out");
System.out.println("Borrower: " + status.getBorrower(checkStatus));
}
else if(Book.OrigBookList.contains(checkStatus) && status.getStatus(checkStatus) == "IN")
{
System.out.println("Status: checked in");
System.out.println("Borrower: none");
}
else if(!(Book.OrigBookList.contains(checkStatus)))
System.out.print("Book is not in library system. Please add the book first.");
}
public void searchPatron() //WORKS!!!
{
Scanner inputread = new Scanner(System.in);
System.out.println("Enter patron full name: ");
String checkPatron = inputread.nextLine();
Book search = new Book(checkPatron);
if(Book.UserList.contains(checkPatron))
{
System.out.println("-------------------------------------------------");
System.out.println("Books checked out: " + search.getBook(checkPatron));
System.out.println("-------------------------------------------------");
}
else
System.out.println("Patron is not part of the library system. Please create new patron first.");
}
}
Since you're calling non static methods of Patron and Book you have to make their objects to call these methods. Only static methods can be called directly on the Class. Check links below for details on static members
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Couple of things to keep in mind
Constructors should be used to create objects only your Library() constructor is doing too much work, try to put it outside constructor.
Your case 11 was not exiting from the loop, I have added System.exit(0) there.
Close the Scanner object using input.close()
Try some exception handling in the code to be safe.
In Java it's convention to keep first letter small in naming non static fields and methods. Check this link https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
Here's the corrected code
import java.awt.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.Collections;
public class Library {
public static void main(String[] args) {
// create new library
Library newLibrary = new Library();
}
public Library() {
Scanner input = new Scanner(System.in);
int choice = 0;
System.out
.println("********************Welcome to the Public Library!********************");
System.out
.println(" Please Select From The Following Options: ");
System.out
.println("**********************************************************************");
while (choice != 9) {
System.out.println("1: Add new patron");
System.out.println("2: Add new book");
System.out.println("3: Edit patron");
System.out.println("4: Edit book");
System.out.println("5: Display all patrons");
System.out.println("6: Display all books");
System.out.println("7: Check out book");
System.out.println("8: Check in book");
System.out.println("9: Search book");
System.out.println("10: Search Patron");
System.out.println("11: Exit");
choice = input.nextInt();
//creating Patron and Book objects
Patron patron = new Patron();
Book book = new Book();
switch (choice) {
case 1: // Add new patron
// ERROR: Patron cannot be resolved or is not a field
patron.newPatron();
break;
case 2: // Add new book
// ERROR: Cannot make a static reference to the non-static
// method
book.addBook();
break;
case 3: // Edit patron name
patron.editName();
break;
case 4: // edit book
// ERROR: Cannot make a static reference to the non-static
// method
book.editBook();
break;
case 5: // display all patrons
System.out.println(Book.UserList);
break;
case 6: // display all books
// System.out.println(Book.OrigBookList);
Book.libraryInventory();
// Book.bookStatus()
break;
case 7: // check out a book
// ERROR: Cannot make a static reference to the non-static
// method
patron.CheckOutBook();
break;
case 8: // check in a book
// ERROR: Cannot make a static reference to the non-static
// method
patron.CheckInBook();
break;
case 9: // search book
// ERROR: Cannot make a static reference to the non-static
// method
patron.bookStatus();
break;
case 10:// search Patron
patron.searchPatron();
break;
case 11: // exit program
//added exit(0)
System.exit(0);
}
}
}
}
Related
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 .
Hello everyone I am an amateur in Java and had some specific questions about a program using ArrayLists. The program is made up of several classes, and its purpose is to add, change, remove, and display friends from a Phone Book. I have the add and display methods done, but I'm having trouble with the remove and change method. I saw a similar case on this site, but it did not help me solve my problems. Any help at all would be much appreciated. This is what I have so far:
package bestfriends;
import java.util.Scanner;
import java.util.ArrayList;
public class BFFHelper
{
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
}
public void addABFF()
{
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();
System.out.println("Enter a nick name: ");
String nickName = keyboard.next();
System.out.println("Enter a phone number: ");
String cellPhone = keyboard.next();
BestFriends aBFF = new BestFriends(firstName, lastName, nickName, cellPhone);
myBFFs.add(aBFF);
}
public void changeABFF()
{
System.out.println("I am in changeBFF");
}
public void displayABFF()
{
System.out.println("My Best Friends Phonebook is: ");
System.out.println(myBFFs);
}
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
{
if(firstName.equalsIgnoreCase(myBFFs.get(i).getFirstName()) && lastName.equalsIgnoreCase(myBFFs.get(i).getLastName()))
{
found = true;
}
else
i++;
}
}
}
That was my Helper Class, for which I'm having trouble with the removeABFF method, and still need to create a changeABFF method from scratch. Next is my main class:
package bestfriends;
import java.util.Scanner;
public class BFFPhoneBook
{
public static void main(String args[])
{
int menuOption = 0;
Scanner keyboard = new Scanner(System.in);
BFFHelper myHelper = new BFFHelper();
do
{
System.out.println("1. Add a Friend");
System.out.println("2. Change a Friend");
System.out.println("3. Remove a Friend");
System.out.println("4. Display a Friend");
System.out.println("5. Exit");
System.out.print("Enter your selection: ");
menuOption = keyboard.nextInt();
switch (menuOption)
{
case 1:
myHelper.addABFF();
break;
case 2:
myHelper.changeABFF();
break;
case 3:
myHelper.removeABFF();
break;
case 4:
myHelper.displayABFF();
break;
case 5:
break;
default:
System.out.println("Invalid option. Enter 1 - 5");
}
} while (menuOption != 5);
}
}
This is my last class:
package bestfriends;
public class BestFriends {
private static int friendNumber = 0;
private int friendIdNumber;
String firstName;
private String lastName;
private String nickName;
private String cellPhoneNumber;
public BestFriends (String aFirstName, String aLastName, String aNickName, String aCellPhone)
{
firstName = aFirstName;
lastName = aLastName;
nickName = aNickName;
cellPhoneNumber = aCellPhone;
friendIdNumber = ++friendNumber;
// friendIdNumber = friendNumber++;
}
public boolean equals(Object aFriend)
{
if (aFriend instanceof BestFriends )
{
BestFriends myFriend = (BestFriends) aFriend;
if (lastName.equals(myFriend.lastName) && firstName.equals(myFriend.firstName))
return true;
else
return false;
}
else
return false;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getNickName()
{
return nickName;
}
public String getCellPhone()
{
return cellPhoneNumber;
}
public int getFriendId()
{
return friendIdNumber;
}
public String toString()
{
return friendIdNumber + ". " + firstName + " (" + nickName + ") " + lastName + "\n" + cellPhoneNumber + "\n";
}
}
To explore and manipulate a arraylist an iterator is used
the object lacks the Setters
declare variables
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
BestFriends best;
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
best= new BestFriends();
}
Delete
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
String name= keyboard.next().toLowerCase();// entry name to be removed
Iterator<BestFriends> nameIter = myBFFs.iterator(); //manipulate ArrayList
while (nameIter.hasNext()){
best = nameIter.next(); // obtained object list
if (best.getNickName().trim().toLowerCase().equals(name)){ // if equals name
nameIter.remove(best); // remove to arraylist
}
}
}
Update
public void changeABFF()
{
System.out.print("Enter a friend's name to be change: ");
String name= keyboard.next().toLowerCase().trim();//entry name to be update
Iterator<BestFriends> nameIter = myBFFs.iterator();
while (nameIter.hasNext()){
best = nameIter.next();
if (best.getNickName().trim().toLowerCase().equals(name)){// if equals name
best.setNickName("NEW DATE");//update data with new data Setters
....
}
}
}
In your remove method you do not accept any input of the values
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
....
As you are using firstNamer and lastName to find the object you needs these values
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();
So i have this homework, to create a java movie program. It should have the add movie (title, actor and date of appearance), show (all the movies added) and remove movie(by movie title) options.
Up till now i was able to create the addMovie(), and showMovie() methods...but i got really stuck ad removeMovies().
Here is the code for the Main.java:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
static Scanner input = new Scanner(System.in);
static ArrayList<Movies> movHolder = new ArrayList<Movies>();
public static void main(String[] args) {
int op = -1;
while (op != 0){
op= menuOption();
switch(op){
case 1:
addMovies();
break;
case 2:
removeMovies();
break;
case 3:
showMovies();
break;
case 0:
System.out.print("\n\nYou have exited the program!");
break;
default:
System.out.println("\nWrong input!");
}
}
}
public static int menuOption(){
int option;
System.out.println("\nMenu\n");
System.out.println("1. Add new movies");
System.out.println("2. Remove movies");
System.out.println("3. Show all movies");
System.out.println("0. Exit program");
System.out.print("\nChoose an option: ");
option = input.nextInt();
return option;
}
public static void addMovies(){
String t, a, d;
input.nextLine();
System.out.println("\n---Adding movies---\n");
System.out.print("Enter title of movie: ");
t = input.nextLine();
System.out.print("Enter actor's name: ");
a = input.nextLine();
System.out.print("Enter date of apearance: ");
d = input.nextLine();
Movies mov = new Movies(t, a, d);
movHolder.add(mov);
}
public static void removeMovies(){
int choice;
System.out.println("\n---Removing movies by title---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
}
public static void showMovies(){
System.out.print("---Showing movie list---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
}
}
And here is the Movies.java with the Movie class:
public class Movies {
private String title;
private String actor;
private String date;
public Movies (String t, String a, String d){
title = t;
actor = a;
date = d;
}
public Movies(){
title = "";
actor = "";
date = "";
}
public String getTitle(){
return title;
}
public String getActor(){
return actor;
}
public String getDate(){
return date;
}
public String toString(){
return "\nTitle: " + title +
"\nActor: " + actor +
"\nRelease date: " + date;
}
}
As you could probably see, i am a very beginner java programmer.
Please, if there is anyway someone could help with the removeMovie() method, i would be very grateful.
Since you have the index of the movie that should be removed (choice - 1) you can use ArrayList.remove(int)
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
movHolder.remove(choice-1);
You can use the remove(int index) method:
public static void removeMovies(){
int choice;
System.out.println("\n---Removing movies by title---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
// Decrement the index because you're asking the user for a 1 based input.
movHolder.remove(choice - 1)
}
}
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.
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