简体   繁体   English

使用Java Streams和Scanners时,我遇到了意想不到的行为

[英]I am getting unexpected behaviour when using Java Streams and Scanners

I recently saw a topic of some Uni coursework which was being conducted by a friend whom was instructed to do it a certain way. 我最近看到一个Uni课程的主题,这个课程是由一位被指示以某种方式完成的朋友进行的。 I thought I'd take the opportunity to jump in on the task. 我以为我会借此机会参加这项任务。

I created a Book class like so: 我像这样创建了一个Book类:

class Book
{
    private String author, title;

    public Book setAuthor(String a)
    {
        author = a;
        return this;
    }

    public Book setTitle(String t)
    {
        title = t;
        return this;
    }

    public String getAuthor() 
    {
        return author;
    }

    public String getTitle()
    {
        return title;
    }
}

The concept is that a user can create multiple books at the start of the program and then search for an author: 这个概念是用户可以在程序开始时创建多本书,然后搜索作者:

private final static int BOOK_NO = 3;
private final static SO instance = new SO(); // This is whatever you called the class

public static void main(String[] args)
{
    Book[] books = new Book[BOOK_NO];
    Scanner kybd = new Scanner(System.in);

    for(int i = 0; i < BOOK_NO; i++)
    {
        books[i] = instance.addBook(kybd, new Book());
    }

    Arrays.stream(instance.findBook(kybd, books)).forEach(o -> {
        System.out.println(o.getTitle() + " by " + o.getAuthor());
    });
}

public Book addBook(Scanner s, Book b)
{

    System.out.println("Enter the Author of this book:");
    b.setAuthor(s.next());

    System.out.println("Enter the Title of this book:");
    b.setTitle(s.next());

    return b;
}

public Book[] findBook(Scanner s, Book[] bs)
{
    System.out.println("Search a book by author:");

    List<Book> finding = Arrays .stream(bs)
            .filter(o -> o.getAuthor().equalsIgnoreCase(s.next()))
            .collect(Collectors.toList());

    System.out.println("Found " + finding.size() + " matches.");

    Book[] output = new Book[finding.size()];
    output = finding.toArray(output);
    return output;
}

Now the whole program works fine, however I am experience unexpected behaviour with the Scanner when it comes to searching for a book. 现在整个程序运行正常,但是在搜索书籍时,我遇到了Scanner的意外行为。 Here is a direct input/output behaviour I am experiencing: 这是我遇到的直接输入/输出行为:

Enter the Author of this book:
Foo
Enter the Title of this book:
Bar
Enter the Author of this book:
Foo
Enter the Title of this book:
FooBar
Enter the Author of this book:
Bar
Enter the Title of this book:
Foo
Search a book by author:
Foo
Foo
Foo
Found 2 matches.
Bar by Foo
FooBar by Foo

As you can see, I am having to type the author of the book into the scanner 3 times before getting any result. 正如您所看到的,我必须在获得任何结果之前将该书的作者键入扫描仪3次。 How can I mitigate this? 我该如何缓解这种情况? What is causing this to happen? 是什么导致这种情况发生?

This is because in your Stream you call next() , so for every Book object in the Stream , the Predicate in the call to filter is applied to it, and next() will be called. 这是因为在您的Stream调用next() ,因此对于Stream中的每个Book对象,将对调用filter中的Predicate应用于它,并调用next() Resolve it to a variable so it isn't called more than once: 将其解析为变量,因此不会多次调用它:

String book = s.next();
List<Book> finding = Arrays.stream(bs)
                           .filter(o -> o.getAuthor().equalsIgnoreCase(book))
                           .collect(Collectors.toList());

filter() accepts a Predicate , which in this case will be something like: filter()接受Predicate ,在这种情况下将是:

Predicate<String> pred = str -> str.equalsIgnoreCase(s.next());

So every time it is applied, next() will be called 所以每次应用时,都会调用next()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java套接字 - 使用IDE时出现意外行为 - Java Sockets - Unexpected behaviour when using an IDE 使用多个扫描仪失败-Java - Using multiple scanners failed - Java 为什么在 JAVA 中使用扫描仪时出现运行时错误 - Why I am getting a RUNTIME ERROR when using Scanner in JAVA 使用varargs时出现意外行为-Java - Getting unexpected behavior when using varargs - java 在Java 8流中使用自定义收集器时获取ClassCastException - Getting a ClassCastException when using a custom Collector with java 8 streams Amazon SQS队列使用Java SDK发送/接收意外行为 - 我做错了什么? - Amazon SQS queue send/receive unexpected behaviour with Java SDK - what am I doing wrong? 尝试输出if else if,else循环。 使用阵列和扫描仪。 我究竟做错了什么? - Trying to output an if else if, else loop. using arrays and Scanners. What am i doing wrong? 在Java(Android)中使用扫描仪有什么意义 - what's the point of using scanners in java (android) 为什么我会收到意外的类型、需要变量的错误? 即使我使用的是变量 - Why am I getting a unexpected type, variable required error? even though I am using a variable 当我在Webdriver中使用Java运行脚本时,我收到错误消息“没有警报处于活动状态” - I am getting error message as “No alert is active” when i run the script using Java in Webdriver
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM