【发布时间】:2016-03-15 00:40:51
【问题描述】:
您好,我正在处理的一个 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
【问题讨论】:
-
那是什么问题?
-
在第 11 行,我目前正在验证输入的数字必须在 0 到 100000000 之间。我需要更改它,以便输入的数字必须是我的数组列表中名为 BookList 的元素,所以我可能会产生错误提示“图书馆中不存在这本书。”
-
直接使用 input.NextInt() 并使用 InputMismatchException 保护块。当这个异常被捕获时,您输入了除整数之外的任何其他内容。如果没有抛出,你现在有你的整数。随时随地使用它来遍历您的书单 ID
标签: java validation validate-request