0

嗨,我正在从事的 uni 项目遇到问题。我正在尝试验证输入,以便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
4

2 回答 2

2

您可以对 Arraylist 使用 .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.
}
于 2015-12-09T16:36:10.203 回答
0

创建一个变量 int isExist = 0; 从用户那里获得输入后……通过数组查看那本书是否存在。然后使 isExist=1; 然后循环只做 if 语句

if( isExist == 0) { 
System.out.println("Book is not found");
}

顺便说一句,一旦你在数组中找到了你想使用的打破循环的书break;

于 2015-12-09T16:34:24.483 回答