我正在尝试制作一个Book Database GUI,在创建的数组中插入每本书的标题,作者和价格。
有一个搜索功能,可以按书名在数据库中搜索特定的书。
但是,我的代码似乎仅对一本书有效,而对多本书无效。
例如,我正在尝试输入10本书的详细信息。
我只能搜索最近创建的书。

我的代码如下:

class Book{
    public String title,author;
    public int price;
    Book(String t,String a,int p){
        this.title=t;
        this.author=a;
        this.price=p;
    }
}

class Swingdemo implements ActionListener{
    Book B[]=new Book[10];

    JLabel jl1;
    JTextField a1,a2,a3,a4;
    JButton j1,j2,j3;
    Swingdemo() {

        JFrame jfrm = new JFrame("Welcome");
        jfrm.setSize(180,300);
        jfrm.setLayout(new FlowLayout());
        jfrm.setDefaultCloseOperation(jfrm.EXIT_ON_CLOSE);
        a1 = new JTextField(8);

        a2 = new JTextField(8);

        a3 = new JTextField(8);

        j1 = new JButton("Create");

        a4 = new JTextField(8);

        j2 = new JButton("Search");
        jl1 = new JLabel("Press a Button");
        j1.setActionCommand("1");
        j2.setActionCommand("2");
        j1.addActionListener(this);
        j2.addActionListener(this);
        jfrm.add(a1);
        jfrm.add(a2);
        jfrm.add(a3);
        jfrm.add(j1);
        jfrm.add(a4);
        jfrm.add(j2);
        jfrm.add(jl1);
        jfrm.setVisible(true);
    }

    int num=0;
    public void actionPerformed(ActionEvent ae){
        if(ae.getActionCommand().equals("1")){
            B[num]=new Book(a1.getText(),a2.getText(),Integer.parseInt(a3.getText()));
            jl1.setText("Book has been added");
            num++;
        }

        else{
            int i;
            for(i=0;i<B.length;i++){
                if(B[i].title.equals(a4.getText()))
                    jl1.setText("Book has been found");
            }
            if(i==B.length)
                jl1.setText("Book was not found");
        }
    }

    public static void main(String []args){
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                new Swingdemo();
            }
        });
    }
}

最佳答案

我更喜欢使用Optional包装而不是局部变量,例如found

Optional<Book> mbyBook = Optional.empty();
for (Book b : B) {
    if (b.title.equals(a4.getText())) {
       mbyBook = Optional.of(b);
       break;
    }
}
if (mbyBook.isPresent()) {
    jl1.setText(String.format("Book has been found %s", mbyBook));
} else {
    jl1.setText("Book was not found");
}

10-06 02:43