I am currently working on a library project where i have an arraylist of customers, which all have their own account, and the customers all have got an arraylist of books.
My LoanBook function adds to the bookarray by first getting index of customers and then index of books in 2 for loops.. Like so:
public void loanBook() {
Scanner in = new Scanner(System.in);
boolean loop3 = true;
System.out.println("So you wanna loan a book? Excellent choice.");
while (loop3) {
System.out.println("Search for the book you're looking for: ");
String bookChoice = in.nextLine();
for (int i=0; i<books.size() && loop3; i++) {
if (books.get(i).toString().contains(bookChoice) == true) {
System.out.println("Looking for: " + books.get(i).toString() + "?");
System.out.println("press y to loan book or n to try again");
String choice1 = in.nextLine();
if (choice1.equalsIgnoreCase("y")) {
for (int j=0; j<customers.size() && loop3; j++) {
if (customers.get(j).getSignedIn() == true) {
customers.get(j).booksLoaned.add(books.get(i));
Timer.delayFunction();
System.out.println(customers.get(j).printBookList());
System.out.println("Returning to main menu");
loop3 = false;
}
}
}
if (choice1.equalsIgnoreCase("n")) {
break;
}
}
}
}
}
The problem is that when i print out the customers individual booklist with this method from the customer class:
public ArrayList<Book> printBookList() {
return booksLoaned;
}
it shows the same booklist for all the customers, so if i add a book in customer 1, customer 2 has it aswell. the BooksLoaned arraylist in my Customer class is not static.
the problem hasn't been solved, i've changed the
customers.get(j).booksLoaned.add(books.get(i));
to
customers.get(j).booksLoaned.add(new Book(books.get(i).toString()));
so it now creates a new object to the array instead of refer to the other array of books. Still all the accounts seems to share booksLoaned which they should not.