Java 我的输入数组一直在写自己
每次我将对象传递给数组时,它都会覆盖上一个条目。有人知道为什么会这样吗 addbook()-当我输入name和author时,它会指定一个值,但当输入另一个title和author时,它会覆盖上一个条目Java 我的输入数组一直在写自己,java,arrays,Java,Arrays,每次我将对象传递给数组时,它都会覆盖上一个条目。有人知道为什么会这样吗 addbook()-当我输入name和author时,它会指定一个值,但当输入另一个title和author时,它会覆盖上一个条目 public class library { static Scanner keyboard = new Scanner(System.in); static int count = 0; public static void main(String [] args){
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
您可能希望使
计数
静态
。我假设你希望每次创作一本新书时计数都上升。如果没有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++;
}
另外,我不知道你打算用loanbook book1代码>,但它在循环中每次都被使用,因此我认为这可能是“它被覆盖”的问题。假设小说
和非小说
扩展借书
此外,我认为在library类中不需要计数。你可以摆脱它
更新:
假设你想要小说
或非小说
书籍(它们都扩展了借书簿),你可能想要这样的东西
loanbook book = new fiction(title,author);
System.out.println(book1.toString());
loanArray[x] = book;
您的loanbook
类中的变量是静态的吗?请给我看那个班。另外,按照惯例,Java类名通常是大写和驼峰大小写的,例如LoanBook
和Library
。这段代码看起来不错。你怎么知道你的数组值写得太多了?是什么让你说“它写得太多了”?定义“将一个对象传递给我的数组”和“覆盖以前的条目”,尤其是“以前的条目”。在执行结束时,addBook
局部变量loanArray
应包含五个元素。这些将被丢弃,因此在方法完成后它们将不可用。他甚至没有在代码中使用count
变量,因此将其设为静态将无济于事。count变量链接到bookIdbookId
打印在toString
中。当它被打印出来时,它会显示sameI不反对你的代码,但是OP的代码没有显示“它是如何被改写的”?在往下看之前先看一下显然你不同意
public static int bookID 0;
public loanbook(String pTitle,String pAuthor){
title = pTitle;
author = pAuthor;
bookId++;
}
loanbook book = new fiction(title,author);
System.out.println(book1.toString());
loanArray[x] = book;