验证java中的用户输入

时间:2015-12-09 16:27:51

标签: java validation validate-request

您好我正在处理我正在处理的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

2 个答案:

答案 0 :(得分:2)

您可以对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.
}

答案 1 :(得分:0)

创建一个变量int isExist = 0;从用户那里获得输入后...浏览数组并查看该书是否存在。然后make isExist = 1;然后循环只做if语句

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

顺便说一下,一旦你在数组中找到了这本书,你想用break;

突破循环