我的输入数组继续写自己

每次我将一个对象传递给我的数组时,它都会覆盖前一个条目。 任何人都能发现为什么会这样吗?

addbook() – 当我输入名称时,作者分配一个值,但是当输入另一个标题和作者时,它会覆盖前一个条目。

public class library { static Scanner keyboard = new Scanner(System.in); static int count = 0; public static void main(String [] args){ addBook(); } // Main end static void addBook(){ loanbook [] loanArray = new loanbook[5]; String title,author; int choice; boolean onLoan; loanbook book1; // TESTING ONLY for(int x = 0; x < 5; x++){ System.out.print("Press 1 for Fiction or 2 for Non Fiction: "); // sub menu for fiction and non fiction choice = keyboard.nextInt(); if (choice == 1){ System.out.println("Please enter book title: "); title = keyboard.nextLine(); title = keyboard.nextLine(); System.out.println("Please enter book author: "); author = keyboard.nextLine(); onLoan = false; // not used yet book1 = new fiction(title,author); System.out.println(book1.toString()); loanArray[x] = new loanbook(title,author); } else if (choice == 2) { System.out.println("Please enter book title: "); title = keyboard.nextLine(); title = keyboard.nextLine(); System.out.println("Please enter book author: "); author = keyboard.nextLine(); onLoan = false; // not used yet book1 = new nonfiction(title,author); System.out.println(book1.toString()); loanArray[x] = new loanbook(title,author); } } } } // Library end 

我的Loanbook课程

 public class loanbook { private String title,author; private int bookID, count = 0; public loanbook(String pTitle,String pAuthor){ bookID = count; title = pTitle; author = pAuthor; count++; } // Constructor public void setTitle(String pTitle){ title = pTitle; } // setTitle protected String getTitle(){ return title; } // getTitle protected String getAuthor(){ return author; } // getAuthor public String toString(){ return " BookID: "+ bookID+"\n" + " Title: "+ getTitle()+"\n" +" Author : "+ getAuthor()+ "\n"; } } // loanbook 

您可能想要count static 。 我假设你每次创建新书时都希望计数增加。 如果没有静态,计数值将不会在创建书籍时持续存在,因此每本书的bookID将始终为0。 这可能就是为什么你认为“它会被覆盖” 。 我不完全确定,因为你还没有真正解释这意味着什么。

 private int bookID; public static int count = 0; <-- static public loanbook(String pTitle,String pAuthor){ bookID = count; title = pTitle; author = pAuthor; count++; } 

或者更好的是,只需避免count变量。 你可以像count一样做。 所以count不必要。

 public static int bookID 0; public loanbook(String pTitle,String pAuthor){ title = pTitle; author = pAuthor; bookId++; } 

另外,我不知道你用loanbook book1;计划什么loanbook book1; ,但它每次都在循环中使用,所以我可以看到这可能是“它被覆盖”的问题。 假设fictionnonfiction扩展loanbook

另外,我认为库类中不需要count 。 你可以摆脱它。

更新:

假设你想要loanbook) in yourfiction或非nonfiction书(并且他们都延伸loanbook) in your可能你想要这样的东西

 loanbook book = new fiction(title,author); System.out.println(book1.toString()); loanArray[x] = book;