您好,我在打印 ArrayList 中的项目时遇到问题。我可以在我的 PatronBorrow 方法中打印出来,但在 PatronList 和 PatronReturn 中它不打印任何东西。谁能告诉我代码有什么问题?非常感谢大家
package proj1;
import java.util.ArrayList;
import java.util.List;
public class Patron {
private int id;
private Book book;
private List<Book> books;
public Patron(int id){
this.id = id;
books = new ArrayList<Book>();
}
public int getID(){
return id;
}
public List<Book> getBooks(){
return books;
}
public void PatronBorrow(String b){
book = new Book(b);
books.add(book);
System.out.println("Patron " + id + " has borrowed " + book.getTitle());
}
public void PatronReturn(String b){
for(Book book : books){
if(book.getTitle().equals(b)){
books.remove(book);
System.out.println("Patron " + id + " has borrowed " + book.getTitle());
}
}
}
public void PatronList(){
for(Book b : books){
System.out.println("Patron " + id + " has borrowed " + books.size() + " item(s)");
System.out.println(b);
}
}
package proj1;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Project1 {
public static boolean isNumeric(String str){
for(char c : str.toCharArray()){
if(Character.isDigit(c)){
return true;
}
}
return false;
}
public static void main(String[] args){
String command;
String line;
Patron patron;
int patronID;
String title;
String newTitle;
String infile = args[0];
if (args.length != 1){
throw new IllegalArgumentException("Enter in file name");
}
try{
Scanner file = new Scanner(new FileInputStream(infile));
while(file.hasNext()){
command = file.next();
if(isNumeric(command)){
patronID = Integer.parseInt(command);
patron = new Patron(patronID);
command = file.next();
if(command.equals("borrow")){
title = file.nextLine();
newTitle = title.substring(2, title.length() - 1);
patron.PatronBorrow(newTitle);
}else if(command.equals("return")){
title = file.nextLine();
newTitle = title.substring(2, title.length() - 1);
patron.PatronReturn(newTitle);
}else if(command.equals("list")){
patron.PatronList();
}
}else{
}
}
}catch (FileNotFoundException e) {
System.out.println("File not found" + e.getMessage());
System.exit(0);
}
}
最佳答案
在使用 Patron
的循环中类,您正在创建一个新的(空白)Patron
每次。
如果您想在赞助人之间切换,您需要做的是 Map<Integer, Patron> patrons
或您的主要功能中的类似内容。而不是创建 new Patron(patronID)
每次,从 patrons
中检索它, 如果那里还没有一个,则只创建一个(并将其存储在 map 中)。
(不过,就您的 Patron
类而言,您可能会发现,如果对该类进行一些实际测试,当您删除一本书时,PatronReturn
经常会抛出异常。ConcurrentModificationException
,即导致您'从您当时正在迭代的列表中删除。请注意。)
关于java - ArrayList 不存储对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15180504/