1

下面的代码首先从文本文件中获取行并将其放入数组中。单击按钮后,程序将询问客户的年龄。然后将此年龄放入 if/else if 块中,以将电影添加到包含适合年龄的电影的新数组中(例如:如果年龄为 5 [我意识到这是不现实的],则新数组将仅包含 G 级电影)。然后程序应该显示一个带有适合年龄的电影标题的 jlist。但是,Jlist 永远不会更新并且无限期地保持空白。

    public class Store extends JFrame {
private JPanel contentPane;
private JTextField BuyAgeInput;
DefaultListModel BasketModel = new DefaultListModel();
DefaultListModel CatModel=new DefaultListModel();
/**
 * Launch the application.
 * @throws FileNotFoundException 
 */
public static void main(String[] args) throws FileNotFoundException {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Store frame = new Store();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
/**
 * Create the frame. 
 **/
public Store() throws FileNotFoundException {
    final Movie[] moviearray=new Movie[100];
    //Open file
    final Scanner reader=new Scanner(new File("movies.txt"));
    //Read movies
    for(int j=0;j<moviearray.length;j++)
    {
        if(reader.hasNext())
        {
            moviearray[j]=new Movie();
            moviearray[j].setTitle(reader.nextLine());
            moviearray[j].setNumber(reader.nextInt());
            reader.nextLine();
            moviearray[j].setGenre(reader.nextLine());
            moviearray[j].setYear(reader.nextInt());
            reader.nextLine();
            moviearray[j].setRating(reader.nextLine());
            moviearray[j].setPrice(reader.nextDouble());
            if(reader.hasNextLine())
                reader.nextLine();
        }
    }
    final Movie[] safemovies=new Movie[100];
    setTitle("Title");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    final JPanel StoreWindow = new JPanel();
    StoreWindow.setBackground(UIManager.getColor("Panel.background"));
    StoreWindow.setBounds(0, 0, 434, 262);
    contentPane.add(StoreWindow);
    StoreWindow.setLayout(null);

    final JPanel BuyAge = new JPanel();
    BuyAge.setBounds(0, 0, 434, 262);
    contentPane.add(BuyAge);
    BuyAge.setLayout(null);

    final JPanel BuyWindow = new JPanel();
    BuyWindow.setBounds(0, 0, 434, 262);
    contentPane.add(BuyWindow);
    BuyWindow.setLayout(null);

    JLabel lblCashier = new JLabel("Cashier");
    lblCashier.setBounds(48, 50, 71, 28);
    StoreWindow.add(lblCashier);
    lblCashier.setHorizontalAlignment(SwingConstants.CENTER);
    lblCashier.setFont(new Font("Perpetua", Font.BOLD, 17));

    JLabel lblCustomer = new JLabel("Customer");
    lblCustomer.setBounds(327, 50, 71, 28);
    StoreWindow.add(lblCustomer);
    lblCustomer.setFont(new Font("Perpetua", Font.BOLD, 17));
    lblCustomer.setHorizontalAlignment(SwingConstants.CENTER);

    JButton StoreBuy = new JButton("Buy");
    StoreBuy.setBounds(298, 168, 126, 23);
    StoreWindow.add(StoreBuy);

    JLabel lblStorewindow = new JLabel("StoreWindow");
    lblStorewindow.setFont(new Font("Arial Black", Font.PLAIN, 11));
    lblStorewindow.setBounds(346, 11, 78, 14);
    StoreWindow.add(lblStorewindow);
    StoreBuy.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            getContentPane().removeAll();
            getContentPane().add(BuyAge);
            validate();
            repaint();
        }
    });

    JButton BuyAdd = new JButton("Add");
    BuyAdd.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
        }
    });
    BuyAdd.setBounds(10, 194, 89, 23);
    BuyWindow.add(BuyAdd);

    JButton BuyRemove = new JButton("Remove");
    BuyRemove.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
        }
    });
    BuyRemove.setBounds(217, 194, 89, 23);
    BuyWindow.add(BuyRemove);

    JButton BuyStore = new JButton("Store (Cancels)");
    BuyStore.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            getContentPane().removeAll();
            getContentPane().add(StoreWindow);
            validate();
            repaint();
        }
    });
    BuyStore.setBounds(307, 228, 117, 23);
    BuyWindow.add(BuyStore);

    JButton BuyConfirm = new JButton("Confirm Purchase");
    BuyConfirm.setBounds(78, 228, 117, 23);
    BuyWindow.add(BuyConfirm);

    JLabel lblBuywindow = new JLabel("BuyWindow");
    lblBuywindow.setFont(new Font("Arial Black", Font.PLAIN, 11));
    lblBuywindow.setBounds(355, 11, 69, 14);
    BuyWindow.add(lblBuywindow);

    JScrollPane scrollPane_1 = new JScrollPane();
    scrollPane_1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane_1.setBounds(10, 35, 152, 148);
    BuyWindow.add(scrollPane_1);
    final JList catList = new JList(CatModel); {}
    scrollPane_1.setViewportView(catList);


    JScrollPane scrollPane_2 = new JScrollPane();
    scrollPane_2.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane_2.setBounds(207, 35, 152, 148);
    BuyWindow.add(scrollPane_2);

    JList buyList = new JList();
    scrollPane_2.setViewportView(buyList);
    buyList.setModel(BasketModel);

    BuyAgeInput = new JTextField();
    BuyAgeInput.setText("Age");
    BuyAgeInput.setBounds(10, 114, 86, 20);
    BuyAge.add(BuyAgeInput);
    BuyAgeInput.setColumns(10);

    final JLabel lblOnlyPutNumbers = new JLabel("Age must contain only numbers.");
    lblOnlyPutNumbers.setVisible(false);
    lblOnlyPutNumbers.setBounds(122, 117, 154, 14);
    BuyAge.add(lblOnlyPutNumbers);

    JButton BuyAConfirm = new JButton("Confirm");
    BuyAConfirm.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            String memberage = BuyAgeInput.getText();
            if(memberage.matches("^[a-zA-Z]+$"))
            {
                lblOnlyPutNumbers.setVisible(true);
            }
            else
            {
                lblOnlyPutNumbers.setVisible(false);
                int customerage=Integer.parseInt(BuyAgeInput.getText());
                    if(customerage<8)
                    {
                        for(int i=0;i<moviearray.length;i++)
                        {
                            if((moviearray[i]!=null)&&moviearray[i].getGenre().equals("G"))
                            {
                                safemovies[i]=new Movie();
                                safemovies[i]=moviearray[i];
                            }
                        }
                    }
                    if(customerage<13)
                    {
                        for(int i=0;i<moviearray.length;i++)
                        {
                            if((moviearray[i]!=null)&&(moviearray[i].getGenre().equals("G")||moviearray[i].getGenre().equals("PG")))
                            {
                                safemovies[i]=new Movie();
                                safemovies[i]=moviearray[i];
                            }
                        }
                    }
                    if(customerage<17)
                    {
                        for(int i=0;i<moviearray.length;i++)
                        {
                            if((moviearray[i]!=null)&&(moviearray[i].getGenre().equals("G")||moviearray[i].getGenre().equals("PG")||moviearray[i].getGenre().equals("PG-13")))
                            {
                                safemovies[i]=new Movie();
                                safemovies[i]=moviearray[i];
                            }
                        }
                    }
                    if(customerage>=17)
                    {
                        for(int i=0;i<moviearray.length;i++)
                    {
                        if(moviearray[i]!=null)
                        {
                            safemovies[i]=new Movie();
                            safemovies[i]=moviearray[i];
                        }
                    }
                }
                for(int i=0;i<safemovies.length;i++)
                {
                    if(safemovies[i]!=null)
                    {
                        CatModel.addElement(safemovies[i].getTitle());
                    }
                }
                catList.setModel(CatModel);
                getContentPane().removeAll();
                getContentPane().add(BuyWindow);
                validate();
                repaint();
            }   
        }
    });
    BuyAConfirm.setBounds(10, 187, 89, 23);
    BuyAge.add(BuyAConfirm);

    JButton btnStorecancels = new JButton("Store (Cancels)");
    btnStorecancels.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            getContentPane().removeAll();
            getContentPane().add(StoreWindow);
            validate();
            repaint();
        }
    });
    btnStorecancels.setBounds(284, 228, 140, 23);
    BuyAge.add(btnStorecancels);

    JLabel lblPleaseEnterYour = new JLabel("Please enter your age. This will determine which movies you can buy.\r\n");
    lblPleaseEnterYour.setBounds(10, 30, 414, 14);
    BuyAge.add(lblPleaseEnterYour);

    JLabel lblBuyage = new JLabel("BuyAge");
    lblBuyage.setFont(new Font("Arial Black", Font.PLAIN, 11));
    lblBuyage.setBounds(344, 11, 80, 14);
    BuyAge.add(lblBuyage);
}

}

(我为长度道歉,但我认为这是尽可能少的。我也忽略了进口)。这是我为 Movie 类提供的代码:

    public class Movie {
public String title;
public int number;
public String genre;
public int year;
public Object rating;
public double price;

public Movie()
{
    title="";
    number=0;
    genre="";
    year=0;
    rating="";
    price=0;
}
public Movie(String t,int n,String g,int y,String r,double p)
{
    title=t;
    number=n;
    genre=g;
    year=y;
    rating=r;
    price=p;
}

public void setTitle(String t)
{
    title=t;
}
public String getTitle()
{
    return title;
}
public void setNumber(int n)
{
    number=n;
}
public int getNumber()
{
    return number;
}
public void setGenre(String g)
{
    genre=g;
}
public String getGenre()
{
    return genre;
}
public void setYear(int y)
{
    year=y;
}
public int getYear()
{
    return year;
}
public void setRating(Object object)
{
    rating=object;
}
public Object getRating()
{
    return rating;
}
public void setPrice(double p)
{
    price=p;
}
public double getPrice()
{
    return price;
}
public void addExisting(int x)
{
    number=number+x;
}
public void takeway(int x)
{
    number=number-x;
}

}

这是我的电影文件的格式:

    Now You See Me
    5
    Action
    2013
    PG-13
    10.00
4

1 回答 1

1

这条线不好:

if((moviearray[i]!=null)&&moviearray[i].getGenre()=="G")

不要使用==. 请改用equals(...)orequalsIgnoreCase(...)方法。了解 == 检查两个对象是否相同,这不是您感兴趣的。另一方面,这些方法检查两个字符串是否具有相同顺序的相同字符,这在这里很重要。所以而不是

if (fu == "bar") {
  // do something
}

做,

if ("bar".equals(fu)) {
  // do something
}

或者,

if ("bar".equalsIgnoreCase(fu)) {
  // do something
}

因此,对于您的程序,请执行以下操作:

if((moviearray[i] != null) && 
   moviearray[i].getGenre().equalsIgnoreCase("G"))

此外,您的 safeMovies 集合应该是 ArrayList 而不是数组。您当前的代码(如果有效)将创建一个包含很多空间隙(非 G 级移动)的数组,当您尝试调用数组项上的方法时,这将导致 NullPointerExceptions 发生。因此,要么使用 ArrayList,要么完全摆脱 safeMovies 并简单地将 Movie 添加到列表的模型中。


也是一个挑剔,这一行:

safemovies[i]=new Movie();

是浪费代码。您创建一个 Movie 对象只是为了在下一行丢弃它——没有意义。


另一个挑剔。这个变量,CatModel,应该是catModel。变量名和方法名都应以小写字母开头,而类名应以大写字母开头。遵循这些和其他 Java 命名和格式约定将使其他人(我们!)更容易理解您的代码。

于 2014-03-09T19:57:35.637 回答