gpt4 book ai didi

java - 如何查看所有 ArrayList 条目并删除特定条目?

转载 作者:行者123 更新时间:2023-12-02 08:36:35 26 4
gpt4 key购买 nike

我有一个客户、客户和主类。我在客户类中有一个 ArrayList 来存储每个客户。我想我已经成功添加客户了。如何显示 ArrayList 中的所有客户以及如何删除特定客户?我正在尝试在客户类中创建一个方法并在主类中调用它。

客户类别:

import java.util.ArrayList;
import java.util.Scanner;

public class customer {


//create variables
private int Id;
private String firstName;
private String lastName;


public customer() {

}


//setters and getters
public int getId() {
return Id;
}

public void setId(int id) {
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;
}



//constructor
public customer(int Id, String firstName, String lastName) {
this.Id = Id;
this.firstName = firstName;
this.lastName = lastName;
}

//get user input
public void customerInfo() {
Scanner input = new Scanner(System.in);

{
while (true) {
//ask user for input and get input
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();


//add customer
customers.add(new customer(id, firstName, lastName));

}

}
}
public void displayCustomers() {
System.out.println("Customer List : ");

}
}

客户类别:


import java.util.ArrayList;
//creates an array of the customers

public final class customers {
public static ArrayList<customer> customers;

public customers() {
customers = new ArrayList<customer>();
}


public static void add(customer customer) {
}

}

主类:

public class Main {
public static void main(String[] args) {

customer customerInfoObject = new customer();
customerInfoObject.customerInfo();

customer displayCustomersObject = new customer();
displayCustomersObject.displayCustomers();

}
}

最佳答案

要打印列表中所有客户的信息,请使用循环。用户可以通过多种方式删除客户。您可以从用户接收一个整数并删除给定索引处的客户。您还可以接收客户名称并将其与客户名称进行循环比较,然后删除具有收到名称的名称。

另外,不要使用空括号。只需在 if 条件前面添加 ! 即可将其反转

关于java - 如何查看所有 ArrayList 条目并删除特定条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55995123/

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