通常,我在扫描数组列表中查找某些元素时没有任何问题。我知道如何构造 while 循环等。但是,在这种情况下,我需要使用扫描仪,但它给出了我的问题,如下所示:
以下代码旨在使用扫描仪输入作者和标题,以检查该确切的书(由作者和标题的精确匹配组成)是否在数组列表中。
很可能我忽略了一些简单的东西,但无论如何,我不需要任何评论来评论这是一个愚蠢的代码等。
public String checkForBookUsingInfo(){
int index = 0;
Book bookObject = null;
String returnValue = "Book not found";
String title = "";
String author = "";
Boolean isFound = false;
while (index <bookList.size() && isFound == false ){
bookObject = bookList.get(index);
System.out.println("Please enter title of book to search for.");
String anyTitle = keybd.next();
System.out.println("Please enter author of book to search for.");
String anyAuthor = keybd.next();
if ((title.equals(anyTitle)) && (author.equals(anyAuthor))){
returnValue = "Book is in library.";
}
index++;
}
return returnValue;
最佳答案
next()
仅返回一个标记(单词),因此对于像 The Prince
这样的数据,第一个 next()
将返回 “The”
第二个 next()
将返回 “Prince”
(因此它不会等待用户的输入,因为它已经拥有其 token )。
如果您想阅读更多内容,请使用 nextLine()
一个单词读取整行。
如果您想在代码中同时使用 next()
和 nextLine()
,您应该阅读 Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods
还有一些其他问题:
- 如果可以找到图书,您没有将
isFound
设置为true
; - 每次迭代书籍时,您都会询问书名和作者,但您应该在迭代之前知道这些信息,因此也许让用户将此信息作为方法参数传递。
- 您正在将用户提供的值与
title
和author
字段中的空字符串 (""
) 进行比较
您的代码可能应该看起来更像:
class Book{
private String author;
private String title;
//getters and setters
}
class Library {
private List<Book> bookList = new ArrayList<Book>();
public String checkForBookUsingInfo(String author, String title){
for (Book book : bookList){
if (book.getAuthor().equals(author) && book.getTitle().equals(title)){
return "Book is in library.";
}
}
return "Book not found in library";
}
public static void main(String[] args) throws Exception {
Scanner keybd = new Scanner(System.in);
Library library = new Library();
//add some books to library
//....
System.out.println("Please enter title of book to search for.");
String anyTitle = keybd.nextLine();
System.out.println("Please enter author of book to search for.");
String anyAuthor = keybd.nextLine();
String stateOfBook = library.checkForBookUsingInfo(anyAuthor, anyTitle);
System.out.println(stateOfBook);
}
}
关于java - Scanner 和 While 循环检查数组列表的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28665482/