每个循环都有麻烦

问题描述 投票:0回答:2

因此,我试图制作一个摆动的GUI,以搜索书籍列表,然后在JTextArea中显示该书籍。这是我的actionPerformed方法

public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equals("Search Books")){
        String bookName = JOptionPane.showInputDialog(this, "Enter books to search"); // prompts user to enter book title
        if (bookName == null){
            sArea.append("Enter a Book");
        }else{
            for (Book b: ban.getListOfBooks()){ //going through list of books to find matching title
                if (bookName.equals(b.getTitle())){ // appends string if it is equal to one of the book names
                    sArea.append(bookName);
                }else{ 
                    sArea.append("Book not found");
                }
            }
        }
    }else{
        ...

所以我的问题是针对每个循环。自然,它将为列表中的每个不相等元素打印“找不到书”。因此,如果我有十本书,并且输入第一本书的名称,它将打印该书,然后打印“找不到书”九次。我该如何重新格式化以仅打印一件事?

java swing for-loop each
2个回答
1
投票

您可以使用boolean found标志,然后检查是否在循环末尾找到了这本书

    }else{
        boolean found = false;
        for (Book b: ban.getListOfBooks()){ //going through list of books to find matching title
            if (bookName.equals(b.getTitle())){ // appends string if it is equal to one of the book names
                sArea.append(bookName);
                found = true;
            }else{ 
            }
        }
        if (!found) sArea.append("Book not found");

    }

0
投票

我将在JList(而不是JTextArea)中显示找到的书。

然后,在完成循环后,您将检查已添加到JList中的项目数。如果数字为0,则显示您的消息。

如果您确实要使用JTextArea,则将获取当前显示在textArea中的字符数并保存该值。在循环结束时,您将当前值与先前值进行比较。如果相同,则显示一条消息。

© www.soinside.com 2019 - 2024. All rights reserved.