Java中基于ArrayList存储数组模拟数据库的账户管理实现问询
Hey Luis, let's tackle your questions one by one and get your customer management program working smoothly! First, let's fix the repetitive input code with a for loop, then add the ID-based operations you need.
1. 用For循环简化客户信息填充
Your original code manually assigns values to each index of newCustomer, which creates a lot of repetitive code. We can define an array of field names first, then use a for loop to iterate through this array, prompt the user for input in sequence, and automatically fill the newCustomer array. This is not only concise but also easier to maintain:
import java.util.ArrayList; import java.util.Scanner; public class CustomersDB { private static Scanner scanner = new Scanner(System.in); private ArrayList<String[]> custList = new ArrayList<>(); // Define customer information field names, corresponding to array indices private static final String[] CUST_FIELDS = { "Name", "Surname", "ID", "Phone", "Email", "Address", "City", "State", "Zip Code" }; public void createCustomer() { String[] newCustomer = new String[9]; // Each customer has 9 fields // Use for loop to iterate through fields and fill the array for (int i = 0; i < CUST_FIELDS.length; i++) { System.out.println(CUST_FIELDS[i] + ": "); newCustomer[i] = scanner.nextLine().trim(); // Trim whitespace from input // Call corresponding set methods (if needed) switch(i) { case 0: setCustName(newCustomer[i]); break; case 1: setCustSurname(newCustomer[i]); break; case 2: setCustID(newCustomer[i]); break; // Fixed wrong method name in your original code // Add other field set methods here } } custList.add(newCustomer); System.out.println("Customer created successfully!"); } // Example set methods (you can refine these with validation logic) private void setCustName(String name) { if (name.isEmpty()) { System.out.println("Warning: Name cannot be empty!"); } } private void setCustSurname(String surname) { // Add validation logic here if needed } private void setCustID(String id) { // Check for duplicate IDs to avoid conflicts if (findCustomerById(id) != null) { System.out.println("Warning: This ID already exists!"); } } }
2. ID-Based Query, Delete, and Edit Operations
The core idea is to iterate through custList and find the customer array matching the target ID (since your ID is stored at index 2 of the String[]). Here are the specific implementations:
2.1 Query Customer by ID
// Find customer by ID, return the corresponding String[], or null if not found public String[] findCustomerById(String targetId) { for (String[] customer : custList) { // Avoid NullPointerException by checking for null first if (customer != null && targetId.equals(customer[2])) { return customer; } } return null; } // Display query results public void displayCustomer(String id) { String[] customer = findCustomerById(id); if (customer != null) { System.out.println("===== Customer Details ====="); for (int i = 0; i < CUST_FIELDS.length; i++) { System.out.println(CUST_FIELDS[i] + ": " + customer[i]); } } else { System.out.println("Customer with ID " + id + " not found!"); } }
2.2 Delete Customer by ID
public boolean deleteCustomer(String targetId) { // Use iterator to avoid exceptions when modifying the collection during iteration for (var iterator = custList.iterator(); iterator.hasNext();) { String[] customer = iterator.next(); if (targetId.equals(customer[2])) { iterator.remove(); System.out.println("Customer deleted successfully!"); return true; } } System.out.println("Customer with ID " + targetId + " not found!"); return false; }
2.3 Edit Customer Information by ID
public boolean editCustomer(String targetId) { String[] customer = findCustomerById(targetId); if (customer == null) { System.out.println("Customer not found!"); return false; } System.out.println("Which field do you want to edit?"); // Print all field options for (int i = 0; i < CUST_FIELDS.length; i++) { System.out.println((i+1) + ". " + CUST_FIELDS[i]); } int choice = scanner.nextInt(); scanner.nextLine(); // Consume the newline character left by nextInt() if (choice < 1 || choice > CUST_FIELDS.length) { System.out.println("Invalid choice!"); return false; } int fieldIndex = choice - 1; System.out.println("Enter new " + CUST_FIELDS[fieldIndex] + ": "); String newValue = scanner.nextLine().trim(); customer[fieldIndex] = newValue; // Call corresponding set methods for validation switch(fieldIndex) { case 0: setCustName(newValue); break; case 1: setCustSurname(newValue); break; case 2: // Check for duplicate ID when editing if (findCustomerById(newValue) != null) { System.out.println("Warning: This ID already exists! Reverting change."); customer[fieldIndex] = targetId; // Revert to original ID return false; } setCustID(newValue); break; } System.out.println("Customer updated successfully!"); return true; }
3. Extra Suggestions
- Use a Class Instead of String Array: While you're using a String array to store customer info now, a more standard approach is to create a
Customerclass with attributes likename,surname,id, etc. This makes the code much more readable and maintainable. For example:
Then useclass Customer { private String name; private String surname; private String id; // Add other attributes, getters, and setters here }ArrayList<Customer>to store data, which makes operations more intuitive. - Input Validation: Add necessary validation when getting user input (e.g., non-empty ID/name, unique ID) to avoid storing invalid data.
- Menu System: Add a main menu to let users choose between create, query, delete, and edit operations for better interactivity.
内容的提问来源于stack exchange,提问作者Luis Fernandes

