I'm still pretty new to coding, so my apologies if this has an obvious fix.
I'm trying to build a library that can store book objects, but before I can work on functionality, I need to get an array sorted out. Java itself does not show any errors in my side bar, but when ran through the console, an error appears.
Below I have posted my Library.java class.
import java.util.Scanner;
public class Library {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Book[] books = new Book[2];
String Title;
String Author;
String BookID;
Boolean onLoan;
int NumberofLoans;
for( int i = 0; i < books.length; i++){
System.out.print("Enter the title of the book: ");
Title = input.next();
books[i] = new Book();
books[i].setTitle(Title);
System.out.println("");
System.out.print("Enter the Author of the book: ");
Author = input.next();
books[i].setAuthor(Author);
System.out.println("");
System.out.print("Enter the Book's ID: ");
BookID = input.next();
books[i].setBookID(BookID);
System.out.println("");
NumberofLoans = 0;
books[i].setNumberofLoans(NumberofLoans);
onLoan = false;
books[i].setonLoan(onLoan);
input.close();
}
for(int i = 0; i < books.length; i++){
System.out.println("Title: " + books[i].getTitle());
System.out.println("Author: " + books[i].getAuthor());
System.out.println("BookID: " + books[i].getBookID());
System.out.println("Times loaned: " + books[i].getNumberofLoans());
System.out.println("In library: " + books[i].getonLoan());
}
}
}
The console error itself, is listed below:
Exception in thread "main" Enter the title of the book:
java.lang.IllegalStateException: Scanner closed
at java.util.Scanner.ensureOpen(Scanner.java:1070)
at java.util.Scanner.next(Scanner.java:1358)
at Library.main(Library.java:19)
Could someone pin-point where in my code the error is coming from? Then, changes I could make to stop this error from occurring?
Just to make sure that everything is listed, I will post Book.java, in case the error originates from in there.
public class Book {
private String Title;
private String Author;
private String BookID;
private Boolean onLoan;
private int NumberofLoans;
public Book(){
Title = new String();
Author = new String();
BookID = new String();
onLoan = false;
NumberofLoans = 0;
}
public void setTitle(String title) {
this.Title = title;
}
public void setAuthor(String author) {
this.Author = author;
}
public void setBookID(String bookID) {
this.BookID = bookID;
}
public void setonLoan(Boolean onLoan) {
this.onLoan = onLoan;
}
public void setNumberofLoans(int numberofLoans) {
this.NumberofLoans = numberofLoans;
}
public String getTitle() {
return Title;
}
public String getAuthor() {
return Author;
}
public String getBookID() {
return BookID;
}
public Boolean getonLoan() {
return onLoan;
}
public int getNumberofLoans() {
return NumberofLoans;
}}
In Library class' first loop is causing this. Specifically, this line:
input.close();
Because you are closing the Scanner before it has been used completely by whole program. Scanner is available first time the loop runs. But after first execution, you close the scanner. Hence for the consecutive loop runs, scanner is closed and hence the error.
Add this line after loop finishes. In other words, something like this:
for( int i = 0; i < books.length; i++){
// ... Whatever
}
input.close();
Related
I'm a new java learner. Now I need to set the bookID from 1000, and according to the total number of input IDs, book author, and book title, respectively show the book's information.
For example, when users enter 2, The Lord of the Rings; J. R. R. Tolkien; The Hunger Games; Suzanne Collins;
The output is Book ID: 1000 Title: The Lord of the Rings Author: J. R. R. Tolkien Status: Available Book ID: 1001 Title: The Hunger Games Author: Suzanne Collins Status: Available.
I have completed part of the programming, but now I do not how to write the code in the BOOK[] array.
code:
import java.util.Scanner;
class Book{
private Integer bookID = 1000;
static Integer nextID;
private String title;
private String author;
private boolean isBorrowed;
public Book(String title, String author){
this.title = title;
this.author = author;
this.isBorrowed = false;
this.nextID = bookID++;
}
public void borrowBook(){
isBorrowed = true;
}
public void returnBook(){
isBorrowed = false;
}
public boolean isBookBorrowed(){
return isBorrowed;
}
public void show() {
System.out.println("Book ID: " + bookID);
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.print("Status: ");
if (isBorrowed)
System.out.println("Not Available");
else
System.out.println("Available");
System.out.println();
}
}
public class MyClass {
public static void main(String args[]) {
Scanner input=new Scanner(System.in);
int num=input.nextInt();
input.nextLine();
Book[] books = new Book[num];
String title;
String author;
for (int i=0; i<num; i++) {
books[i] =input.nextBook();
title = input.nextLine();
author = input.nextLine();
}
}
}
The following is my programming code, please help me see how to write the code of the array part, thank you very much!
This is how it should be done:
nextId must be static because it's the one and only variable that has your last book id.
bookID should not be static because it's different for each book.
Book class:
class Book{
private static Integer nextID = 1000;
private Integer bookID;
private String title;
private String author;
private boolean isBorrowed;
public Book(String title, String author){
this.title = title;
this.author = author;
this.isBorrowed = false;
this.bookID = nextID++;
}
public void borrowBook(){
isBorrowed = true;
}
public void returnBook(){
isBorrowed = false;
}
public boolean isBookBorrowed(){
return isBorrowed;
}
public void show() {
System.out.println("Book ID: " + bookID);
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.print("Status: ");
if (isBorrowed)
System.out.println("Not Available");
else
System.out.println("Available");
System.out.println();
}
}
Main class:
import java.util.Scanner;
public class MyClass{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num = input.nextInt();
input.nextLine();
Book[] books = new Book[num];
String title;
String author;
for (int i = 0; i < num; i++) {
title = input.nextLine();
author = input.nextLine();
books[i] = new Book(title,author);
}
for (int i = 0; i < num; i++) {
books[i].show();
}
}
}
The following code has a "database" of 2 books. The user is prompted to enter the book id as you stated, it starts with 1000. If the book is found they see your information via the show() method. If this isn't what you want let me know. OR if you want to add a feature that allows the user to input books we can do that too..
Please always give user prompts like "enter a number" when you use scanner.
I went ahead and added so that the user can enter a book and immediately see that the book was stored with the correct id. its alternate main below
import java.util.Scanner;
public class Book {
private static Integer nextID = 1000;
private Integer bookID;
private String title;
private String author;
private boolean isBorrowed;
public Book(String title, String author){
this.title = title;
this.author = author;
isBorrowed = false;
bookID = nextID++;
}
public void borrowBook(){
isBorrowed = true;
}
public void returnBook(){
isBorrowed = false;
}
public boolean isBookBorrowed(){
return isBorrowed;
}
public void show() {
System.out.println("Book ID: " + bookID);
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.print("Status: ");
if (isBorrowed)
System.out.println("Not Available");
else
System.out.println("Available\n");
}
public static void main(String[] args) {
// here we will create an array of 2 books as your data
Book books[] = new Book[2];
books[0] = new Book("blah", "blah bhal hald");
books[1] = new Book("java", "girl power");
Scanner input = new Scanner(System.in);
System.out.println("Enter the book id:");
int num = input.nextInt();
for (int i = 0; i < books.length; i++){
if (books[i].bookID == num){
books[i].show();
}
}
}
}
alternate main:
```public static void main(String[] args) {
// here we will allow the user to input book data and see the data
// returned with the new id.
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of books you wish to add:");
int num = input.nextInt();
input.nextLine();
Book[] books = new Book[num];
String title;
String author;
for (int i = 0; i < num; i++) {
System.out.println("enter the title:");
title = input.nextLine();
System.out.println("enter the author");
author = input.nextLine();
books[i] = new Book(title,author);
System.out.println("The book you entered is:");
books[i].show();
}
}
I'm trying to create a program that takes book names, number of pages, and publishing year as user input. When user does not input anything to name field, program should ask user what will be printed: only names of the books or all information given by user. Here is my main code:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int index = 0;
Scanner reader = new Scanner(System.in);
ArrayList<Books> book = new ArrayList<>();
while (true) {
System.out.println("Name of the book: ");
String name = reader.nextLine();
if (name.isEmpty()) {
break;
}
System.out.println("Number of pages: ");
int pages = Integer.parseInt(reader.nextLine());
System.out.println("Year: ");
int year = Integer.parseInt(reader.nextLine());
book.add(new Books(name,pages,year));
}
while (true) {
System.out.println("What do you want to print?");
String whatwillbeprinted = reader.nextLine();
if (whatwillbeprinted.equals("everything")) {
while(index < book.size()) {
System.out.println(book.get(index));
index++;
}
}
if (whatwillbeprinted.equals("names")) {
while(index < book.size()) {
// print only names of the books
}
}
}
}
}
And here is my Java class named Books:
public class Books {
private String name;
private int pages;
private int year;
public Books(String name, int pages, int year) {
this.name = name;
this.pages = pages;
this.year = year;
}
#Override
public String toString() {
return this.name + ", " + this.pages + ", " + this.year;
}
}
Everything operates correctly until that last while-statement. How can I print only first elements of my objects (names of the books)? Thanks in advance.
public class Books {
private String name;
private int pages;
private int year;
public Books(String name, int pages, int year) {
this.name = name;
this.pages = pages;`
this.year = year;
}
#Override
public String toString() {
return this.name + ", " + this.pages + ", " + this.year;
}
public String getName(){
return name;
}
}
Then calling book.getName () you can get the name of the book, now just write a loop in which display the name of each book
P.S confusion about the name of the class: The name Books is incorrect since the class stores information about only one book. Book - correct title
Book Title Code:
for(int i = 0;i<book.lenght;i++)
{
System.out.println("Name of book: " + book[i].getName());
}
I've been having this issue with a 'Loanbook' method, the function of it is to increment the 'numOnLoan' variable stored in an object ArrayList by 1, however when i run the method it doesn't seem to change the value.
//Allows loaning of books
public static void Loanbook(Scanner sc, ArrayList<Book> books){
System.out.println("Please enter a book title");
if(sc.hasNext()){
String criteria = sc.nextLine();
for (int i = 0; i < books.size(); i++){
if(criteria.equals(books.get(i).getBookTitle())){
System.out.println("The book " + books.get(i).getBookTitle() + " there are " + books.get(i).getNumInStock() + " in stock");
books.get(i).setNumOnLoan(books.get(i).GetNumOnLoan()+1);
System.out.println("number on loan: " + books.get(i).GetNumOnLoan()); break;
}
} System.out.println("Book Loaned");
LibraryTester.MenuReturn(sc, books);
}
LibraryTester.MenuReturn(sc, books);
}
i suspect this is an issue with the logic of the code by however i edit it, the code doesn't seem to do what i want.
Edit:
book.java
public class Book {
private int id;
private String bookTitle;
private String authorName;
private int bookReleaseYear;
private int numOnLoan;
private int numInStock;
//constructor
public Book(int id, String bookTitle, String authorName, int bookReleaseYear, int numOnLoan, int numInStock) {
this.id = id;
this.bookTitle = bookTitle;
this.authorName = authorName;
this.bookReleaseYear = bookReleaseYear;
this.numOnLoan = numOnLoan;
this.numInStock = numInStock;
}
//Getters/Setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBookTitle() {
return bookTitle;
}
public void setBookTitle(String bookTitle) {
this.bookTitle= bookTitle;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public int GetNumOnLoan() {
return numOnLoan;
}
public void setNumOnLoan(int numOnLoan) {
this.numOnLoan = numOnLoan;
}
public int getNumInStock() {
return numInStock;
}
public void setNumInStock(int numInStock) {
this.numInStock = numInStock;
}
public int getBookReleaseYear() {
return bookReleaseYear;
}
public void setBookReleaseYear(int bookReleaseYear) {
this.bookReleaseYear = bookReleaseYear;
}
Library.java
import java.util.ArrayList;
import java.util.Scanner;
public class Library {
public ArrayList<Book> books = new ArrayList<Book>();
public Library(){
super();
}
//Getters/Setters
public Library(ArrayList<Book> books) {
this.books = books;
}
public ArrayList<Book> getBooks() {
return books;
}
public void setBooks(ArrayList<Book> books) {
this.books = books;
}
//Methods
//Allows loaning of books
public static void Loanbook(Scanner sc, ArrayList<Book> books){
System.out.println("Please enter a book title");
if(sc.hasNext()){
String criteria = sc.nextLine();
for (int i = 0; i < books.size(); i++){
if(criteria.equals(books.get(i).getBookTitle())){
System.out.println("The book " + books.get(i).getBookTitle() + " there are " + books.get(i).getNumInStock() + " in stock");
books.get(i).setNumOnLoan(+1);
System.out.println("number on loan: " + books.get(i).GetNumOnLoan()); break;
}
} System.out.println("Book Loaned");
LibraryTester.MenuReturn(sc, books);
}
LibraryTester.MenuReturn(sc, books);
}
}
public static void Returnbook(Scanner sc, ArrayList<Book> books){
System.out.println("Please enter a book title");
if(sc.hasNext()){
String criteria = sc.nextLine();
for (int i = 0; i < books.size(); i++){
if(criteria.equals(books.get(i).getBookTitle())){
System.out.println("The book " + books.get(i).getBookTitle() +
" is in stock," + " there are " + books.get(i).getNumInStock() + " in stock and " + books.get(i).GetNumOnLoan() + " out on loan");
books.get(i).setNumOnLoan(-1);; break;
}
} System.out.println("Book returned");
LibraryTester.MenuReturn(sc, books);
}
}
LibraryTester.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class LibraryTester {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Library lib = new Library();
ArrayList<Book> books = lib.getBooks();
books = Library.CreateBooksArrayList();
MenuInput(sc, books);
sc.close();
lib.setBooks(books);
}
//prints menu
public static void PrintMenu(){
System.out.println("Public Library Menu System");
System.out.println("---------------------------");
System.out.println("1: Add Book");
System.out.println("2: Search for book");
System.out.println("3: Loan Book");
System.out.println("4: Return Book");
System.out.println("5: Amend Book Details");
System.out.println("6: Display all Books");
System.out.println("7: Delete a Book");
System.out.println("8: Other Options");
System.out.println("9: Exit system");
System.out.println("----------------------------");
}
// Allows menu input
public static void MenuInput(Scanner sc, ArrayList<Book> books){
int input = 0;
PrintMenu();
if(sc.hasNextInt()){
input = sc.nextInt();
switch(input){
case 1:Library.AddBook(sc, books);
case 2:Library.SearchBooks(sc, books);;
case 3:Library.Loanbook(sc,books);
case 4:Library.Returnbook(sc, books);
case 5:Library.AmendDetails(sc,books);
case 6:Library.DisplayAllBooks(sc,books);
case 7:Library.Removebook(sc, books);;
case 8:OtherMenu(sc,books);
case 9:System.exit(0);
}
} else {
System.out.println("Please enter a number");
}
}
//Returns user to main menu
public static void MenuReturn(Scanner sc, ArrayList<Book> books){
System.out.println("Press any key to return to the main menu");
if(sc.hasNextLine()){
sc.nextLine();
MenuInput(sc, books);
}
}
}
EDIT: I seem to get the output:
Please enter a book title
Input: book1
Please enter a book title
The book book1 is in stock, there are 5 in stock and 1 out on loan
Book returned
Press any key to return to the main menu
Final Edit: Fixed the issue, the code was not running due to an issue with the if statement, when i removed it there was a problem with all the text appearing at once, which was fixed with am extra 'sc.nextLine'. The issue with the ReturnBook running without call was due to lack of a 'break;' in the menu system.
Thanks everybody for your help, especially Shreyans Sheth
I just dug deep into your code. It seems you had a nasty bug (If it is one). I'll be addressing this specific line in your question: "the function of it is to increment the 'numOnLoan' variable stored in an object ArrayList by 1, however when i run the method it doesn't seem to change the value."
Original method:
public void setNumOnLoan(int numOnLoan)
{
this.numOnLoan= numOnLoan;
}
Method call in Loanbook:
books.get(i).setNumOnLoan(1);
In the LoanBook method, you are simply passing '+1' as a parameter and everytime, only 1 is being assigned. Here's what you need to do.
public void setNumOnLoan(int numOnLoan)
{
//When numOnLoan is 1, as you have passed everytime
//the current value gets incremented by one. I think that is what you wanted.
this.numOnLoan += numOnLoan; //You add it to the existing variable
}
You really should have named that function something else. I'm pretty sure there are more bugs out there but does THIS accomplish what you wanted?
Output:
(First call to Loanbook)
Please enter a book title
input :bbbbb
The book bbbbb there are 5 in stock
number on loan: 2
Book Loaned
(Second call to Loanbook)
Please enter a book title
input: bbbbb
The book bbbbb there are 5 in stock
number on loan: 3
Book Loaned
I'm learning java and my programming skills are are good. I have been asked to find out the problem with codes below. when I paste them on netbeans, the error that had been detected was in the public class CheckoutProgram (String wordIn = Keyboard.readInput(); and wordIn = Keyboard.readInput();) and I noticed that the public static void method was empty but I'm not sure it has anything to do with the error. I have tried to find a solution myself but I can't sort it out. Can you help me with this issue? please
import java.io.*;
import java.text.DecimalFormat;
public class CheckoutProgram {
public static void main (String[] args) {
}
public void start() {
SalesItem[] items = getStock();
System.out.print("Type item code (press enter to finish):");
String wordIn = Keyboard.readInput();
SalesItem[] goods = new SalesItem[1000];
int count = 0;
while (wordIn.length()>=4 && wordIn.length()<=4){
for (int i=0;i<items.length;i++) {
if (items[i] != null && wordIn.equals(items[i].getItemCode())){
System.out.println(items[i]);
goods[count] = items[i];
}
}
System.out.print("Type item code (press enter to finish):");
wordIn = Keyboard.readInput();
count++;
}
System.out.println();
System.out.println("==========Bill==========");
double amountDue = 0.0;
for (int i=0; i<count; i++){
System.out.println(goods[i]);
amountDue = amountDue + goods[i].getUnitPrice();
}
System.out.println();
System.out.println("Amount due: $" + new DecimalFormat().format(amountDue));
System.out.println("Thanks for shopping with us!");
}
// method to read in "stock.txt" and store the items for sale in an array of type SalesItem
private SalesItem[] getStock(){
SalesItem[] items = new SalesItem[1000];
try {
BufferedReader br = new BufferedReader(new FileReader("stock.txt"));
String theLine;
int count = 0;
while ((theLine = br.readLine()) != null) {
String[] parts = theLine.split(",");
items[count] = new SalesItem(parts[0],parts[1],Double.parseDouble(parts[2]));
if (parts.length==4){
String discount = parts[3];
String numPurchases = discount.substring(0, discount.indexOf("#"));
String price = discount.substring(discount.indexOf("#")+1);
items[count].setNumPurchases(Integer.parseInt(numPurchases));
items[count].setDiscountedPrice(Double.parseDouble(price));
}
count++;
}
}
catch (IOException e) {
System.err.println("Error: " + e);
}
return items;
}
}
import java.text.DecimalFormat;
public class SalesItem {
private String itemCode; //the item code
private String description; // the item description
private double unitPrice; // the item unit price
// An item may offer a discount for multiple purchases
private int numPurchases; //the number of purchases required for receiving the discount
private double discountedPrice; // the discounted price of multiple purchases
// the constructor of the SalesItem class
public SalesItem (String itemCode, String description, double unitPrice){
this.itemCode = itemCode;
this.description = description;
this.unitPrice = unitPrice;
}
// accessor and mutator methods
public String getItemCode(){
return itemCode;
}
public void setItemCode(String itemCode){
this.itemCode = itemCode;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description = description;
}
public double getUnitPrice(){
return unitPrice;
}
public void setUnitPrice(double unitPrice){
this.unitPrice = unitPrice;
}
public int getNumPurchases(){
return numPurchases;
}
public void setNumPurchases(int numPurchases){
this.numPurchases = numPurchases;
}
public double getDiscountedPrice(){
return discountedPrice;
}
public void setDiscountedPrice(double discountedPrice){
this.discountedPrice = discountedPrice;
}
// the string representation of a SalesItem object
public String toString(){
return description + "/$" + new DecimalFormat().format(unitPrice);
}
}
Keyboard most likely doesn't exist. It isn't a part of the standard Java library. You would have to import a class that uses Keyboard if you are trying to use some custom class to read user input.
I assume you are getting the error because you do not have the class Keyboard. Check for a file called Keyboard.java.. This is more of a comment than an answer.
Firstly you are using public for a class CheckoutProgram so the file name should be same as the class name when you used public access specifier for a class.
Secondly the Keyboard class is missing in your program so please check with these issues.
Could you please help me figure out how will I make it possible to create a delete command?
in selection 5. I must use array not ArrayList neither Vector?
//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\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;
}
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.lang.reflect.Array;
import java.util.Scanner;
import java.util.Arrays;
public class Management {
public Book[] books =new Book [60];
String Sisbn;
int current = 0;
Library lib = new Library ();
Scanner input = new Scanner( System.in );
//Number 1
public void AddBook(Book vivlio)
{
books[current]=vivlio;
current++;
}
//Number 2
public Book findBookByTitle(String title)
{
Book searchBook = null;
for (Book vivlio : books)
{
if(vivlio.getName().equalsIgnoreCase(title))
{
searchBook = vivlio;
System.out.println("New name of book:");
vivlio.setName(input.nextLine());
System.out.println("New Author of book:");
vivlio.setAuthor(input.nextLine());
System.out.println("New isbn of book:");
vivlio.setIsbn(input.nextLine());
System.out.println("New number of copies of book:");
vivlio.setNumber(input.nextInt());
break; }
}
return searchBook;
}
public String getSisbn() {
return Sisbn;
}
public void setSisbn(String sisbn) {
Sisbn = sisbn;
}
public Book[] getBooks() {
return books;
}
public void setBooks(Book[] books) {
this.books = books;
}
public int getCurrent() {
return current;
}
public void setCurrent(int current) {
this.current = current;
}
//Number3
public Book findBookByISBN(String isbn)
{
Book searchBook = null;
for (Book vivlio : books)
{
if(vivlio.getIsbn().equalsIgnoreCase(isbn))
{
searchBook = vivlio;
String book = vivlio.getName();
lib.once=vivlio.getName();
System.out.println(lib.once);
break;
}
}
return searchBook;
}
//Number 4
public void PrintAllBooks()
{
for (int i=0;i<current;i++)
{
Book b = books[i];
System.out.println(b.name);
}
}
//number 5
public Book DeleteWithIsbn(String isbn)
{
Book searchBook = null;
for (Book vivlio : books)
{
if(vivlio.getIsbn().equalsIgnoreCase(isbn))
{
searchBook = vivlio;
books[current]=null;
for (int i=0;i<current;current--)
{
Book b = books[i];
System.out.println(b.name);
break;
}
}
}
return searchBook;
}
}
Your code doesn't attempt to 'delete' it still finds. Try the following instead:
(Untested but gives you the idea)
public boolean DeleteWithIsbn(String isbn) {
int index = 0;
for (Book vivlio : books) {
if(vivlio.getIsbn().equalsIgnoreCase(isbn)) { //find the right book
for (int i = index; i < books.length - 1; i++) {
books[i] = books[i+1]; //move all the other books up
}
books[books.length -1] = null; //reset the last one in the array
return true;
}
count++;
}
return false;
}
This method will return false if it cannot find the book. It returns true otherwise.
Of course this all assumes that the book only ever exists once in the array.
First, fix your indentation on your if/else statements, and consider using a case statement instead.
Second, your Selection 5 isn't actually deleting anything -- it's just setting String empty to the next line. Get the user-inputted ISBN with Scanner, and make sure to call Book.DeleteBookWithISBN(isbn) with that isbn. Then it'll do what you want :)