【发布时间】:2019-09-20 03:02:55
【问题描述】:
我有一个 ArrayList,它要求用户输入,然后存储每个员工的详细信息。如何显示存储在此 ArrayList 中的所有内容或搜索特定员工?然后我将如何从 ArrayList 中编辑或删除该员工?我有两个类,一个是 salesPerson - 我有所有变量、setter、getter 和构造函数,而 salesPersonMain - 我有提示用户输入、存储到数组等的地方。
我可以将员工添加到 ArrayList 并在结束输入循环时查看它们。
public class salesPersonMain {
public static void main(String[] args) throws InputValidationException {
Scanner input = new Scanner(System.in);
List<salesPerson> sPerson = new ArrayList<salesPerson>();
while (true) {
System.out.println("Enter id (press 'q' to quit): ");
String temp = input.nextLine();
if (temp.equals("q")) break;
int id = Integer.parseInt(temp);
System.out.println("Enter first name:");
String firstName = input.nextLine();
System.out.println("Enter last name:");
String lastName = input.nextLine();
//save in array list
sPerson.add(new salesPerson(id, firstName, lastName));
}
for (salesPerson salesPerson : sPerson) {
System.out.println(salesPerson);
}
}
}
salesPerson 类:
import java.util.ArrayList;
public class salesPerson{
//create variables for sales person
private int id;
private String firstName;
private String lastName;
public salesPerson() {
}
//Setters and getters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) throws InputValidationException {
if (firstName.matches("\\p{Upper}(\\p{Lower}){2,20}")) {
} else {
throw new InputValidationException();
}
{
this.firstName = firstName;
}
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName)throws InputValidationException {
if (lastName.matches("\\p{Upper}(\\p{Lower}){2,20}")) {
} else {
throw new InputValidationException();
}
{
this.lastName = lastName;
}
}
public void setCurrentCarMake(String currentCarMake) throws InputValidationException {
if (currentCarMake.matches("(\\p{Alpha}{2,14})")) {
} else {
throw new InputValidationException();
}
{
this.currentCarMake = currentCarMake;
}
}
public String getCurrentCarModel() {
return currentCarModel;
}
public void setCurrentCarModel(String currentCarModel) throws InputValidationException {
if (currentCarModel.matches("(\\p{Alnum}{1,10})")) {
} else {
throw new InputValidationException();
}
{
this.currentCarModel = currentCarModel;
}
}
//create constructor
public salesPerson(int id, String firstName, String lastName) throws InputValidationException {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return id + ", " + firstName + " " + lastName;
}
}
【问题讨论】:
-
你能举例说明你想要搜索/删除的内容吗?现在这个问题太广泛了,无法回答。包括 salesPerson 类也会有所帮助。
-
如果销售人员离开公司,我想搜索他们并将他们从 ArrayList 中删除。我打算开设一个客户课程,因此我希望能够更改客户详细信息,例如电话号码。
-
如果您打算定期编辑/删除项目,我建议您使用某种
Map,键是salesPerson 的ID,因此您拥有O(1) 访问权限,然后只需要一定要使用Map 方法做任何你想做的事情。