JAVA So i have this code that i am using arrays of [60] and when i use the add command it rewrites all the previous statements i made

StackOverflow https://stackoverflow.com/questions/23454489

  •  15-07-2023
  •  | 
  •  

Pergunta

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


}
Foi útil?

Solução

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.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top