public class Catalogue() {
private List<Book> booksAvailable;
private List<Book> booksRented:
public Catalogue() {
booksAvailable.add(new Book("Matrix", 1999, new Genre("SciFi"), 3));
booksAvailable.add(new Book("Jurassic Park", 1999, new Genre("SciFi"), 3));
boosAvailable.add(new Book("Terminator", 1999, new Genre("SciFi"), 3));
booksRented = new LinkedList<Book> ();
}
public void rentBook() {
System.out.println("Rent a book:");
System.out.println("Enter the title of a book you want to rent: ");
String name = In.NextLine();
for (Book book: booksAvailable) {
if (book.getName.equals(name)) {
System.out.println("Renting " + name);
booksAvailable.remove(book);
booksRented.add(book);
break;
} else {
System.out.println("No such books found");
}
}
}
}
运行此代码时只能租用Matrix手册。当我试图租用另一本像侏罗纪公园的书时,它说没有找到书。当我关闭程序并再次运行并尝试租用第二本书时,它再次说未找到书籍。请帮我解决这个问题。我在这段代码中遇到了什么问题。感谢
答案 0 :(得分:1)
当你在迭代时修改列表的其他人指出了它是危险的。
我建议您尝试使用HashMap,尤其是如果name是您正在查看的唯一字段。
public class Catalogue {
private Map<String, Book> booksAvailable;
private Map<String, Book> booksRented;
public Catalogue() {
booksAvailable = new HashMap<>();
booksAvailable.put("Matrix", new Book("Matrix", 1999, new Genre("SciFi"), 3));
booksAvailable.put("Jurassic Park", new Book("Jurassic Park", 1999, new Genre("SciFi"), 3));
booksAvailable.put("Terminator", new Book("Terminator", 1999, new Genre("SciFi"), 3));
booksRented = new HashMap<>();
}
public void rentBook() {
System.out.println("Rent a book:");
System.out.println("Enter the title of a book you want to rent: ");
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
if (booksAvailable.containsKey(name)) {
Book book = booksAvailable.get(name);
System.out.println("Renting " + name);
booksAvailable.remove(name);
booksRented.put(name, book);
} else {
System.out.println("No such books found");
}
}
}
答案 1 :(得分:0)
当您致电booksAvailable.remove()
时,它将从当前迭代中有效删除。
因此,当您访问next()
时,可能会导致意外行为。
修改强> 由于您的代码处理,您不能租借第一本书以外的其他书籍。
你在System.out.println("No such books found");
语句内部循环中有else
。因此,如果您输入的书不是第一本书,则测试失败并打印语句。
要纠正此问题,您可以使用标记来指示是否找到某本书,并在循环外打印该语句;
boolean rented = false;
for (Book b : books) {
if (found) {
rented = true;
}
}
if (!rented) {
// print no such book message
}
答案 2 :(得分:0)
我只是尝试了你的代码(在修改它以进行编译之后)并且它有效。
但是,当运行例如Jurasic Park
时,它会说找不到该书,然后它将租用它,因为该print语句在for循环中。
我尝试重写它以使用流和选项,我得到了似乎正在运行的代码
public void rentBook() {
System.out.println("Rent a book:");
System.out.println("Enter the title of a book you want to rent: ");
String name = "Jurassic Park";
Optional<Book> book = booksAvailable.stream().filter(b -> b.name.equals(name)).findFirst();
if(book.isPresent()) {
System.out.println("Renting " + name);
booksAvailable.remove(book.get());
booksRented.add(book.get());
}
else
System.out.println("No such book found");
}