-2

这是一个在数组列表中存储员工信息(薪水、姓名、ID#、雇用日期)的程序。当被调用时(按下“listButton”后),它会在字段中列出此信息以供雇主查看。员工需要从列表中删除一个员工,有一个 removeButton,那么什么可以让雇主从员工列表中删除一个名字?

public class EmployeeView extends FrameView {

    class Company {
        String ID, firstName, lastName, annualSal, startDate, mileage;

        Company (String _ID, String _firstName,String _lastName, String _annualSal, String _startDate) {
            ID = _ID;
            firstName = _firstName;
            lastName = _lastName;
            annualSal = _annualSal;
            startDate = _startDate;
        }
    }

    /** Define the ArrayList */
    ArrayList <Company> employee = new ArrayList <Company>();

    String ID, firstName, lastName, annualSal, startDate;

    public EmployeeView(SingleFrameApplication app) {
       //GUI stuff...
    }

    private void AddActionPerformed(java.awt.event.ActionEvent evt) {

        ID = IDField.getText();
        firstName = firstNameField.getText();
        lastName = lastNameField.getText();
        annualSal = annualSalField.getText();
        startDate = startDateField.getText();

        Company c = new Company(ID, firstName, lastName, annualSal, startDate);
        employee.add(c);
    }

    private void ListActionPerformed(java.awt.event.ActionEvent evt) {

        String temp = "";

        for (int x=0; x<=employee.size()-1; x++) {
            temp = temp + employee.get(x).ID + " "
                    + employee.get(x).firstName + " "
                    + employee.get(x).lastName + " "
                    + employee.get(x).annualSal + " "
                    + employee.get(x).startDate + "\n";
        }
        employeeTArea.setText(temp);

}

    private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {
    //My attempt... it didn't do anything though           
            int remove = 0;

            for (int j = 0; j < employee.size()-1; j++) {
                if (remove == Integer.parseInt(IDField.getText())) {

                   employee.remove(j);
                }
            }
    }
4

2 回答 2

2

您正在初始化remove=0,您想要做的是:

for (int j = 0; j < employee.size()-1; j++) {
                if (j == Integer.parseInt(IDField.getText())) {
                   employee.RemoveAt(j);
                }
            }

您不需要删除变量。这提供IDField.getText()employee您要从ArrayList

于 2013-05-01T22:37:20.967 回答
0

您可以消除 for 循环,只需执行employee.remove(company)即可。

于 2013-05-01T22:39:37.370 回答