每次我将一个对象传递给我的数组时,它都会覆盖前一个条目。任何人都能发现为什么会这样吗?
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
我的借阅手册
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
答案 0 :(得分:1)
您可能想要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;
计划什么,但每次在循环中使用它,所以我可以看到这是可能的“它被覆盖” 问题。假设fiction
和nonfiction
延长loanbook
此外,我认为库类中不需要count
。你可以摆脱它。
更新:
假设你想要fiction
或nonfiction
本书(他们都延伸loanbook) in your
loanArray`你可能想要这样的东西
loanbook book = new fiction(title,author);
System.out.println(book1.toString());
loanArray[x] = book;