如您所见,我正在尝试从在MongoDB中创建的图书编号列表中找回一本书。我正在从数据库中恢复书籍的状态,但是当我尝试提取列出书籍的编号时,由于以下原因,我无法:
bookNum = book.get(choice-1);
下面列出了我的代码,以为您提供帮助。任何帮助将不胜感激。
//Find a book in the bookInfo database
Scanner input = new Scanner(System.in);
System.out.print("Enter the Title of a Book: ");
String book = input.nextLine();
int referenceNum = 0;
BasicDBObject query = new BasicDBObject();
query.put("Title",
new BasicDBObject("$regex", book)
.append("$options", "i"));
MongoCursor<Document> cursor = collection.find(query).iterator();
while(cursor.hasNext()) {
Document bookInfo = cursor.next();
referenceNum++;
System.out.println(referenceNum + ")" + bookInfo.getString("Title"));
}
System.out.print("\nEnter selection number (0 to quit): ");
Scanner inp = new Scanner(System.in);
int choice = inp.nextInt();
String bookNum;
// choice not 0 and not too high
if(choice > 0 && choice <= referenceNum) {
bookNum = book.get(choice - 1);
}
else {
bookNum = "0";
}
}
最佳答案
问题:从数据库中获取的书籍列表未存储在任何地方
以下是更新的代码:
// Find a book in the bookInfo database
Scanner input = new Scanner(System.in);
System.out.print("Enter the Title of a Book: ");
String book = input.nextLine();
int referenceNum = 0;
BasicDBObject query = new BasicDBObject("Title", new BasicDBObject("$regex", book).append("$options", "i"));
MongoCursor<Document> cursor = collection.find(query).iterator();
List<String> books = new ArrayList<>();
while (cursor.hasNext()) {
Document bookInfo = cursor.next();
referenceNum++;
System.out.println(referenceNum + ")" + bookInfo.getString("Title"));
books.add(bookInfo.getString("Title"));
}
System.out.print("\nEnter selection number (0 to quit): ");
int choice = input.nextInt();
String bookNum;
// choice not 0 and not too high
if (choice > 0 && choice <= referenceNum) {
bookNum = books.get(choice - 1);
} else {
bookNum = "0";
}
// Closing the scanner
input.close();