您好,我正在处理的大学项目遇到问题。我正在尝试验证输入,以便尝试借书时输入的 BookID
仅当它存在于名为“BookList
”的数组中时才有效。目前我让它工作,以便它验证它以确保输入的是整数,而不是字母或负数。
我已经尝试了无数次,但我完全卡住了?任何提示或帮助,我将不胜感激。 谢谢
//loan a book method
public void loanBook() {
int loanID;
do {
System.out.println("Please enter the Book ID of the book that you wish to borrow");
while (!input.hasNextInt()) { // checking that the ID entered is an integer - validation
System.out.println("That is not an integer");
input.nextLine(); //pushing the scanner on
}
loanID = input.nextInt(); //setting the loanID variable equal to the input from the scanner.
}
while (loanID < 0 || loanID > 100000000); //VALIDATION - NEED TO CHANGE SO THAT WHILE LOAN ID EXISTS IN ARRAY LIST ????
for (int i = 0; i < BookList.size(); i++) { //for loop to go through and check for the ID entered to remove the book that it corresponds to
if (BookList.get(i).getBookID() == loanID ) {
System.out.println("The book named : " + BookList.get(i).getTitle() + " has now been taken out on loan. Please return within 2 weeks!");
BookList.get(i).setStatus("On Loan");;
}//end of if statement
}//end of for loop
} //end of return book method
最佳答案
您可以对 Arraylists 使用 .contains() 方法。您只需确保根据项目的状态删除项目即可。
if(bookList.contains(loanID)){
//logic for book exists
}else{
//book is on loan.
}
现在,正如我所说,您需要确保您正在进行适当的验证,以删除借出的书籍等,才能使其发挥作用。您现在的逻辑方式是在循环中进行大量不必要的工作。这样您就可以轻松扫描列表并找到所需的项目。当然,有更好的方法来设置列表等,但这应该可以使您的代码非常相似。
编辑
您请求了解在验证该项目存在后如何找到该项目的索引。这个还是很简单的。一旦您验证了该项目存在,您将使用以下行:
int index = bookList.indexOf(loanID);
这将返回 ArrayList 中书籍位置的索引。获得索引后,您可以开始执行之前所做的所有操作:
bookList.get(index).getBookId();
或
bookList.get(bookList.indexOf(itemId)).getBookId();
这几乎与您之前所做的完全一样,但减少到 3 行,甚至可以更短。
if (BookList.contains(loanID)) {
int index = BookList.indexOf(loanId);
if (!BookList.get(index).getStatus().equals("On Loan")) {
System.out.println("The book named: " + BookList.get(index).getTitle() + " has now been taken on loan.");
BookList.get(index).setStatus("On Loan.");
}else{
System.out.println("Book is on loan already.");
}
}else{
//logic for not existing.
}
关于java - java中验证用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34183930/