gpt4 book ai didi

java - 我的输入数组不断地 self 写入

转载 作者:行者123 更新时间:2023-12-01 13:41:44 25 4
gpt4 key购买 nike

每次我将一个对象传递给数组时,它都会覆盖前一个条目。有人能找出为什么会发生这种情况吗?

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

我的贷款簿类(class)

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

最佳答案

您可能希望将计数设为静态。我假设您希望每次创建新书时计数都会增加。如果没有静态,计数值将不会在每次创建图书时持续存在,因此每本书的 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; 做什么,但它每次都会在循环中使用,所以我可以看到这是可能的”它正在被覆盖”问题。假设 fictionnonfiction 扩展 loanbook

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

更新:

假设您想要在您的 loanArray` 中添加 fictionnonfiction 书(它们都扩展了 loanbook),您可能需要这样的



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

关于java - 我的输入数组不断地 self 写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20694498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com