从数组中删除对象[java] [英] deleting an object from an array [java]

查看:147
本文介绍了从数组中删除对象[java]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序要求用户输入5人的名字,姓氏和年龄并将其存储在数组中。我想编写一个方法,询问用户要从数组中删除谁,然后删除该雇员。我知道在数组中,您不能从技术上从数组中删除对象,而只能将其替换。
这是我到目前为止所做的:

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.")
       }


}

我的问题是不会将数组大小减少1,而只是将我要删除的人替换为数组中的最后一个人。我的输出中数组中的最后一个雇员重复了两次(在最后一个索引和我要删除的人的索引中)如何解决?

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?

推荐答案

您可以在要删除员工时将其替换为null。插入新员工时,您可以先查看一个空索引并将其放置。

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.")
  }
}

这篇关于从数组中删除对象[java]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆