2016-10-25 2 views
-1

Я начинающий Java-программист, который в настоящее время работает над проектом. Программа должна быть в состоянии:Удаление данных о сотрудниках с использованием ArrayLists не работает

  • добавить вошли данные о сотрудниках записи
  • удалить сотрудника из
  • список записей все записи в JTextArea.

В настоящее время мои функции добавления и списка работают, но метод удаления не работает.

Проблема, кажется, происходит здесь:

else if (event.getSource().equals(remove)) { 
     for (int i = 0; i < ids.size(); i++) { 
      if (Integer.parseInt(idInput.getText()) == ids.get(i)) { 
       ids.remove(i); 
       firstNames.remove(i); 
       lastNames.remove(i); 
       salary.remove(i); 
       startDates.remove(i); 
       display.setText("Employee #" + ids.get(i) + " has been   removed from the records."); 
      } else { 
       display.setText("Error: employee ID# does not exist, try again."); 
      } 
     } 
    } 

Вот полный код для контекста:

public class Employee implements ActionListener { 

public static String div = "-----------------------------------"; 
public static ArrayList<Integer> ids, salary; 
public static ArrayList<String> firstNames, lastNames, startDates; 
public static JTextField idInput, firstInput, lastInput, salaryInput, startInput; 
public static JTextArea display; 
public static JButton add, remove, list; 

public static void main(String[] args) { 
    // Defining all array lists 
    ids = new ArrayList(); 
    salary = new ArrayList(); 
    startDates = new ArrayList(); 
    firstNames = new ArrayList(); 
    lastNames = new ArrayList(); 

    // Fonts 
    Font titleFont = new Font("Courier New", 1, 24); 
    Font subFont = new Font("Courier New", 1, 16); 

    // Frame 
    JFrame frame = new JFrame("Employee Records"); 
    frame.setSize(550, 450); 
    frame.setLocationRelativeTo(null); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setResizable(false); 

    // Container 
    JPanel container = new JPanel(); 
    container.setLayout(null); 
    frame.setContentPane(container); 

    // Title 
    JLabel title = new JLabel("Employee Records"); 
    title.setFont(titleFont); 
    title.setBounds(160, 10, 250, 24); 

    // Lablels and text fields 
    JLabel employeeID = new JLabel("Employee ID#: "); 
    employeeID.setBounds(5, 50, 190, 16); 
    employeeID.setFont(subFont); 
    idInput = new JTextField(); 
    idInput.setBounds(160, 47, 150, 22); 

    JLabel employeeFirst = new JLabel("First Name: "); 
    employeeFirst.setBounds(5, 85, 190, 16); 
    employeeFirst.setFont(subFont); 
    firstInput = new JTextField(); 
    firstInput.setBounds(160, 82, 150, 22); 

    JLabel employeeLast = new JLabel("Last Name: "); 
    employeeLast.setBounds(5, 120, 190, 16); 
    employeeLast.setFont(subFont); 
    lastInput = new JTextField(); 
    lastInput.setBounds(160, 117, 150, 22); 

    JLabel annualSalary = new JLabel("Annual Salary: "); 
    annualSalary.setBounds(5, 155, 190, 16); 
    annualSalary.setFont(subFont); 
    salaryInput = new JTextField(); 
    salaryInput.setBounds(160, 152, 150, 22); 

    JLabel start = new JLabel("Start Date: "); 
    start.setBounds(5, 190, 190, 14); 
    start.setFont(subFont); 
    startInput = new JTextField(); 
    startInput.setBounds(160, 187, 150, 22); 

    // Buttons 
    add = new JButton("Add (REQUIRES ALL FIELDS)"); 
    add.setBounds(330, 47, 200, 20); 
    add.addActionListener(new Employee()); 

    remove = new JButton("Remove (by ID#)"); 
    remove.setBounds(330, 72, 200, 20); 
    remove.addActionListener(new Employee()); 

    list = new JButton("List"); 
    list.setBounds(330, 97, 200, 20); 
    list.addActionListener(new Employee()); 

    // Text area 
    display = new JTextArea(); 
    display.setEditable(false); 
    JScrollPane scrollPane = new JScrollPane(display); 
    scrollPane.setBounds(5, 217, 535, 200); 

    // Adding everything 
    container.add(title); 
    container.add(scrollPane); 
    container.add(employeeID); 
    container.add(idInput); 
    container.add(employeeFirst); 
    container.add(firstInput); 
    container.add(employeeLast); 
    container.add(lastInput); 
    container.add(annualSalary); 
    container.add(salaryInput); 
    container.add(start); 
    container.add(startInput); 
    container.add(add); 
    container.add(remove); 
    container.add(list); 

    // Extras 
    frame.toFront(); 
    frame.setVisible(true); 
} 

public void actionPerformed(ActionEvent event) { 
    if (event.getSource().equals(add)) { 
     if (idInput.getText().equals("") || firstInput.getText().equals("") || lastInput.getText().equals("") 
       || salaryInput.getText().equals("") || startInput.getText().equals("")) { 
      display.setText("Error, please fill every field."); 
     } else { 
      ids.add(Integer.parseInt(idInput.getText())); 
      firstNames.add(firstInput.getText()); 
      lastNames.add(lastInput.getText()); 
      salary.add(Integer.parseInt(salaryInput.getText())); 
      startDates.add(startInput.getText()); 
      display.setText("Employee added to record(s)."); 
     } 
    } else if (event.getSource().equals(remove)) { 
     for (int i = 0; i < ids.size(); i++) { 
      if (Integer.parseInt(idInput.getText()) == ids.get(i)) { 
       ids.remove(i); 
       firstNames.remove(i); 
       lastNames.remove(i); 
       salary.remove(i); 
       startDates.remove(i); 
       display.setText("Employee #" + ids.get(i) + " has been removed from the records."); 
      } else { 
       display.setText("Error: employee ID# does not exist, try again."); 
      } 
     } 
    } else { 
     display.setText(null); 
     for (int i = 0; i < ids.size(); i++) { 
      display.append(div + "\nEmployee ID#: " + ids.get(i) + "\nFirst Name: " + firstNames.get(i) 
        + "\nLast Name: " + lastNames.get(i) + "\nAnnual Salary ($): " + salary.get(i) 
        + "\nStart Date: " + startDates.get(i) + "\n"); 
     } 
    } 
} 

ответ

4

Вы переборе до, не вниз.

При удалении элемента, все элементы справа получить перемешиваются одно место влево, так что индексы остальных элементов все снижение на 1.

Если вы итерацию вниз, вы не должны это проблема:

for (int i = ids.size() - 1; i >= 0; i--) { 
    // same code you have now 
} 

Еще лучше, если использовать Iterator на сбор, и вызвать iterator.remove() когда iterator.next() возвращает значение, которое вы хотите удалить (этот код слева как упражнение для читателя).