gpt4 book ai didi

java - 如何从数组中添加或删除某些内容?

转载 作者:行者123 更新时间:2023-12-01 13:14:09 26 4
gpt4 key购买 nike

我正在编写这个程序,它将接收用户中 5 个不同人的姓名、年龄和工资,并将它们放入一个数组中。

然后我想编写一个方法,询问用户另一个姓名、年龄和薪水,并将其添加到数组中。还有一种方法,用于查找已在数组中的某人的姓名,并从数组中删除具有该年龄的人的信息。

第一种方法会将数组大小增加 1,第二种方法会将数组大小减少 1。到目前为止,这就是我所拥有的:

ArrayList<details> details = new ArrayList<details>();

for(int x = 0; x < 4; x++) {

Scanner scan = new Scanner(System.in);

System.out.println("Enter the first name: ");
String firstName = scan.nextLine();

System.out.println("Enter the last name: ");
String lastName = scan.nextLine();

System.out.println("Enter the age: ");
int age = scan.nextInt();

System.out.println("Enter the salary: ");
double salary = scan.nextDouble();

details.add (new details(firstName, lastName, age, salary));

}

我不知道该怎么做。我需要一些帮助!谢谢!

最佳答案

您可以拥有一个 Person 类,其中包含您需要的类变量(姓名、年龄、薪水)

class Person {
private int age;
private dobule salary;
private String firstname;
private String lastname;
}

为每个类变量定义 getter 和 setter 方法。例如

public void setAge(int age){
this.age = age;
}
public int getAge(){
return this.age;
}

在您的主类中,当您执行此操作时,从 STDIN 读取输入。为 5 个人中的每一个实例化 Person 对象。

Person employee = new Person();
employee.setAge(x);
employee.setFirstName(x);
employee.setLastName(y);
employee.setSalary(y);

现在,您可以 add您列表中的每个人以及 remove他们也是。

要删除任何人,您必须通过名称通过 ArrayList 搜索该人。这将迭代 ArrayList 的长度并比较每个的名称。

最终的类(class)看起来像,

public class Solution{

private ArrayList<Person> details = new ArrayList()<Person>;

public static void main(){
// Here you loop for reading from STDIN as you are already doing.
// addPerson() would be used to add to ArrayList and removePerson() for the other
}
public addPerson(String firstName, String lastName, int age, int salary){
//Create the Person object
details.add(<person object>);
}
public removePerson(name){
details.remove(index);
// to get index it would require iterating over the ArrayList.
// It would be better if you use a Map instead (as other suggest)
// with name as the key
}
}

希望这有帮助。

关于java - 如何从数组中添加或删除某些内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22595327/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com