My program asks the user to enter the first name, last name and age of 5 people and stores them in an array. I want to write a method that asks the user whom they want to delete from the array and then deletes that employee. I know in arrays you cannot technically delete an object from an array, just replace it.
This is what I've done so far:
private void deleteEmployee(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first name of the employee you want to delete from the list")
String name = scan.nextLine();
for (int i = 0; i < employees.length; i++) {
if (employees[i].getFirstName().equals(name)){
employees[i] = employees[employees.length - 1];
break;
}
if (i == employees.length - 1) {
System.out.println("That requested person is not employed at this firm.")
}
}
My problem is that it does not decreases the array size by 1, it just replaces the person I want to delete with the last person in my array. My output has the last employee in the array repeated twice (in it's last index and in the index of the person I wanted to delete) How do I fix this?
解决方案
you can replace the employee with null whenever want to delete it. when inserting a new emplyee, you can first look at a null index and place it.
private void deleteEmployee(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first name of the employee you want to delete from the list")
String name = scan.nextLine();
for (int i = 0; i < employees.length; i++) {
if (employee[i] != null && employees[i].getFirstName().equals(name)){
employees[i] = null;
break;
}
if (i == employees.length - 1) {
System.out.println("That requested person is not employed at this firm.")
}
}