Method wont increment an int variable inside an object ArrayList? - java

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

Related

how to output the book's title, author, and show the bookID seperately?

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();
}
}

Why are the attributes of the objects from my ArrayList returning null?

I'm writing code for a library (of books) in Java. I have a Book class with three attributes: Title, Author, and Genre. Genre is stored as an int because there are not that many:
public class Book {
public String title;
public String author;
public int genre;
public Book() {
this.title = title;
this.author = author;
this.genre = genre;
}
public void setBookTitle(String newBookTitle) {
this.title = newBookTitle;
}
public void setBookAuthor(String newBookAuthor) {
this.author = newBookAuthor;
}
public void setBookGenre(int newBookGenre) {
this.genre = newBookGenre;
}
public String getBookTitle() {
return title;
}
public String getBookAuthor() {
return author;
}
public int getBookGenre() {
return genre;
}
public String toString() {
LibraryDatabase libraryDatabase = new LibraryDatabase();
return ("Title: "+this.getBookTitle() +
"Author: " +this.getBookAuthor()+"Genre: " + this.getBookGenre() //edit this part to refer the integer to a String
);
}
}
I have a library database class for storing an ArrayList of books:
import java.util.*;
public class LibraryDatabase extends Book {
ArrayList<Book> bookDatabase;
public LibraryDatabase() {
}
public void books() {
Book book1 = new Book();
book1.setBookTitle("Harry Potter");
book1.setBookAuthor("J.K. Rowling");
book1.setBookGenre(1);
}
public ArrayList<Book> getArrayList() {
return bookDatabase;
}
}
Lastly, I have a Customer class that basically just organizes all of the above into a user-friendly interface:
import java.io.*;
import java.util.*;
public class Customer {
public Customer() {
}
public void run() {
System.out.print("Welcome to Generic Library Service. Please enter your name.");
Scanner kbEater = new Scanner(System.in);
String customerName = kbEater.nextLine();
System.out.println("Would you like to borrow, return, or donate a book?");
System.out.println(" 1. Borrow");
System.out.println(" 2. Return");
System.out.println(" 3. Donate");
Scanner kbNeeder = new Scanner(System.in);
int customerChoice = kbEater.nextInt();
switch (customerChoice) {
case 1: borrow();
break;
//case 2: returnBook();
//case 3: donate();
}
}
public void printGenres() {
System.out.println(" 1. Fantasy");
System.out.println(" 2. Science Fiction");
System.out.println(" 3. Dystopian");
System.out.println(" 4. Action & Adventure");
System.out.println(" 5. Mystery");
System.out.println(" 6. Horror");
System.out.println(" 7. Thriller & Suspense");
System.out.println(" 8. Historical Fiction");
System.out.println(" 9. Romance");
System.out.println(" 10. Graphic Novel");
System.out.println(" 11. Young Adult");
System.out.println(" 12. Children's");
System.out.println(" 13. Memoir & Biography");
System.out.println(" 14. Food");
System.out.println(" 15. Art & Photography");
System.out.println(" 16. Self-improvement");
System.out.println(" 17. History");
System.out.println(" 18. Travel");
System.out.println(" 19. Humor");
System.out.println(" 20. How-to");
System.out.println(" 21. Science & Tech");
}
public void borrow() {
System.out.println("What is the genre of the book you're looking for?");
printGenres();
Scanner kbMeter = new Scanner(System.in);
int genre = kbMeter.nextInt();
System.out.println("Do you want to see titles, or are you looking for a particular author?");
System.out.println(" 1. Titles now");
System.out.println(" 2. Search by author");
Scanner kbLeader = new Scanner(System.in);
int titleOrSearch = kbLeader.nextInt();
switch(titleOrSearch) {
case 1:
titlesNow();
break;
case 2:
//method for searching by author
}
}
public void titlesNow() {
LibraryDatabase libraryDatabase = new LibraryDatabase("1", "1", 2);
System.out.println(toString());
}
}
And this is the output:
Welcome to Generic Library Service. Please enter your name. **Username**
Here are our books:
Title: nullAuthor: nullGenre: 0
Why is this happening? Why are the attributes returning null? I want to list all the books' titles, authors, and genres from the Book ArrayList. Because there's currently only one book, it should print out that book(Harry Potter by J.K. Rowling).
Your problem is here, in the constructor:
public Book() {
this.title = title;
this.author = author;
this.genre = genre;
}
You are assigning title, author, genre to themselves, which are all null. To fix this, simply pass in some parameters to the constructor:
public Book(String title, String author, int genre) {
this.title = title;
this.author = author;
this.genre = genre;
}
and everything should work instead of having to use the setter methods.
The printing wrong is because of the fact that you don't save your book1 anywhere. In your constructor for LibraryDatabase, add bookDatabase = new ArrayList<>(); and at the end of the books() function, add a bookDatabase.add(book1);.
Also, note that your LibraryDatabase does not do anything in your toString() method.
Change your LibraryDatabase as below
import java.util.*;
public class LibraryDatabase extends Book {
ArrayList<Book> bookDatabase;
public LibraryDatabase() {
}
public void books() {
Book book1 = new Book();
book1.setBookTitle("Harry Potter");
book1.setBookAuthor("J.K. Rowling");
book1.setBookGenre(1);
bookDatabase.add(book1);
}
public ArrayList<Book> getArrayList() {
return bookDatabase;
}
}
Add that book1 to your arraylist. Also add #null_awe code. you are missing that too .
public Book(String title,String author,int genre) {
this.title = title;
this.author = author;
this.genre = genre;
}

Error of "variable might not initialized" while trying to use a class object as a parameter of a method, tried to use a IF to avoid the problem (JAVA)

I'm learning JAVA and I was making the code for a product sales system in a store as an example. So I created the Product, Customer and Sale classes.
In my menu I check if there is a registered product or customer, if yes I call my sales method that has both parameters. However, NetBeans notifies an error that the variable has not been initialized even with the logic not to start the sale if the registration has not been done before.
My basic code:
"variable product might not have been initialized"
"variable customer might not have been initialized"
//Main
//Reg a client and a product, then perform a sale.
package store;
import java.util.Random;
import java.util.Scanner;
public class Store {
static boolean flagProduct=false, flagCustomer=false;
public static void main(String[] args) {
menu();
}
public static void menu() {
System.out.println("\n Choose option:\n"
+ "1 - Product Registration\n"
+ "2 - Customer Registration\n"
+ "3 - Sell\n"
+ "4 - End\n"
);
Scanner scanner = new Scanner(System.in);
int select = scanner.nextInt();
switch (select) {
case 1:
Product product = RegistProduct();
System.out.print("\n Cod product : " + product.getCodProduct());
System.out.print("\n Price product : " + product.getPriceProduct());
System.out.print("\n Quantity product : " + product.getQuantProduct());
menu();break;
case 2:
Customer customer = RegistCustomer();
System.out.print("\n Cod Customer : " + customer.getCodCustomer());
System.out.print("\n Customer name: " + customer.getName());
menu();break;
case 3:
if(flagProduct == true && flagCustomer==true){
Sale sale = sell(product, customer); // *****where the error happens*****
System.out.print("\n Sale code : " + sale.getCodSale());
System.out.print("\n Customer name: " + customer.getName());
System.out.print("\n Cod product : " + product.getCodProduct()+ " -- Quantity:" + sale.getQuantSale()+ " -- Total:" + sale.getValueSale());
} else if(flagProduct == true && flagCustomer==false){
System.out.println("First register the customer ");
menu();break;
} else if(flagProduct == false && flagCustomer==true){
System.out.println("First register the product");
menu();break;
} else
System.out.println("First register the customer and product");
menu();break;
case 4:
break;
default:
System.out.println("Error");
menu();
}
}
public static Product RegistProduct(){
Product product = new Product();
java.util.Scanner scanner = new Scanner(System.in);
System.out.print("Product code:\n");
product.setCodProduct(scanner.nextInt());
System.out.print("Product price:\n");
product.setPriceProduct(scanner.nextFloat());
System.out.print("Product quantity:\n");
product.setQuantProduct(scanner.nextInt());
flagProduct = true;
return product;
}
public static Customer RegistCustomer(){
Customer customer = new Customer();
java.util.Scanner scanner = new Scanner(System.in);
System.out.print("Customer name:\n");
customer.setName(scanner.nextLine());
System.out.print("Customer code:\n");
customer.setCodCustomer(scanner.nextInt());
flagCustomer=true;
return customer;
}
public static Sale Sell(Product product, Customer customer){
java.util.Scanner scanner = new Scanner(System.in);
Random num = new Random();
int codSale = num.nextInt(9999);
Sale sale = new Sale();
sale.setCodSale(codSale);
System.out.print("Customer code:");
int codSaleCustomer = scanner.nextInt();
while (codSaleCustomer != customer.getCodCustomer()){
System.out.print("Non-existent code. Please enter a valid code:\n");
codSaleCustomer = scanner.nextInt();
}
System.out.print("Product code:");
int codSaleProduct = scanner.nextInt();
while (codSaleProduct != product.getCodProduct()){
System.out.print("Non-existent code. Please enter a valid code:\n");
codSaleProduct = scanner.nextInt();
}
System.out.print("Quantity of products purchased:\n");
sale.setQuantSale(scanner.nextInt());
sale.setValueSale(sale.getQuantSale()*product.getPriceProduct());
product.setQuantProduct(product.getQuantProduct() - sale.getQuantSale());
System.out.print("Remaining quantity in stock: "+ product.getQuantProduct());
return sale;
}
}
//Class Product
package store;
public class Product {
private int codProduct;
private float priceProduct;
private int quantProduct;
public int getCodProduct() {
return codProduct;
}
public void setCodProduct(int codProduct) {
this.codProduct = codProduct;
}
public float getPriceProduct() {
return priceProduct;
}
public void setPriceProduct(float priceProduct) {
this.priceProduct = priceProduct;
}
public int getQuantProduct() {
return quantProduct;
}
public void setQuantProduct(int quantProduct) {
this.quantProduct = quantProduct;
}
}
//Class customer
package store;
public class Customer {
private int codCustomer;
private String name;
public int getCodCustomer() {
return codCustomer;
}
public void setCodCustomer(int codCustomer) {
this.codCustomer = codCustomer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//Class sale
package store;
public class Sale extends Product{ //I dnno if extends is necessary
private int codSale;
private int quantSale;
private float valueSale;
public int getCodSale() {
return codSale;
}
public void setCodSale(int codSale) {
this.codSale = codSale;
}
public int getQuantSale() {
return quantSale;
}
public void setQuantSale(int quantSale) {
this.quantSale = quantSale;
}
public float getValueSale() {
return valueSale;
}
public void setValueSale(float valueSale) {
this.valueSale = valueSale;
}
}

Displaying a multiple object arraylist?

I am curious as to how would I show a multiple object arraylist in Java. The array list contains both string and int.
This is the class of which I am making a arraylist of.
public class Movie
{
public int rating;
public String title, directorName, actorOne, actorTwo, actorThree;
public Movie(String Title, String Director, String ActorOne, String ActorTwo, String ActorThree, int Rating)
{
title = Title;
directorName = Director;
actorOne = ActorOne;
actorTwo = ActorTwo;
actorThree = ActorThree;
rating = Rating;
}
public void setTitle(String Title)
{
title = Title;
}
public String getTitle()
{
return title;
}
public void setDirector(String Director)
{
directorName = Director;
}
public String getDirector()
{
return directorName;
}
public void setActorOne(String ActorOne)
{
actorOne = ActorOne;
}
public String getActorOne()
{
return actorOne;
}
public void setActorTw0(String ActorTwo)
{
actorTwo = ActorTwo;
}
public String getActorTwo()
{
return actorTwo;
}
public void setActorThree(String ActorThree)
{
actorThree = ActorThree;
}
public String getActorThree()
{
return actorThree;
}
}
This is my main class
import java.io.*;
import java.util.*;
public class Database
{
Scanner input = new Scanner(System.in);
boolean start;
ArrayList<Movie> movie = new ArrayList<Movie>();
String title, director, actOne, actTwo, actThree;
int rating;
public Database()
{
// initialise instance variables
this.display();
}
public void display()
{
while (start = true)
{
System.out.println("Welcome to the Movie Database");
System.out.println
(
"Select an option \n" +
"1 Find Movie \n" +
"2 Add Movie \n" +
"3 Delete Movie \n" +
"4 Display Favourtite Movies \n" +
"5 Exit Database \n"
);
int choice = input.nextInt();
input.nextLine();
switch(choice)
{
case 1:
break;
case 2:
this.addMovie();
break;
case 3:
break;
case 4:
break;
case 5:
this.exit();
break;
default:
System.out.println("Invalid selection.");
break;
}
}
}
public void exit()
{
System.out.println("Exiting");
start = false;
System.exit(0);
}
public void addMovie()
{
System.out.println("Insert Movie Name: ");
title = input.nextLine();
System.out.println("Insert Director Name: ");
director = input.nextLine();
System.out.println("Insert Actor One Name: ");
actOne = input.nextLine();
System.out.println("Insert Actor Two Name: ");
actTwo = input.nextLine();
System.out.println("Insert Actor Three Name: ");
actThree = input.nextLine();
System.out.println("Insert Movie Rating: ");
rating = input.nextInt();
movie.add(new Movie(title, director, actOne, actTwo, actThree, rating));
}
}
I just wish to see if I my program is actually adding to array list.
Thank you
You may find helpful overriding toString method in the movie class and then printing the arrayList everytime you do something with it...
System.out.println("actual state of the list: "+movie);
and override the toString method in the movie class... somthing descripting the object... like:
#Override
public String toString() {
return "Movie [rating=" + rating + ", title=" + title + ", directorName=" + directorName + ", actorOne="
+ actorOne + ", actorTwo=" + actorTwo + ", actorThree=" + actorThree + "]";
}

How to remove an element previously added into an array?

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 :)

Categories