面向对象程序中电话本条目相邻重复检测功能实现求助
Looks like you need to build a phonebook system that handles adjacent entry checks, duplicate detection, and entry counting. Let's break this down step by step, using your existing Name and PhoneNumber classes as a foundation.
Key Requirements Recap
- If adjacent entries have the same name but different phone numbers: Show a warning and output the second entry.
- If adjacent entries have identical name and phone number: Show a duplicate error (don't add the entry).
- Track the total number of processed entries (even duplicates count as processed).
Step 1: Ensure Name and PhoneNumber Have Proper Equality Checks
First, your Name and PhoneNumber classes need to override equals() (and hashCode(), for best practice) so we can accurately compare entries. Here's how you might implement them:
Name Class Example
import java.util.Objects; public class Name { private String firstName; private String lastName; public Name(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } // Getters public String getFirstName() { return firstName; } public String getLastName() { return lastName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Name name = (Name) o; return Objects.equals(firstName, name.firstName) && Objects.equals(lastName, name.lastName); } @Override public int hashCode() { return Objects.hash(firstName, lastName); } @Override public String toString() { return firstName + " " + lastName; } }
PhoneNumber Class Example
import java.util.Objects; public class PhoneNumber { private String number; public PhoneNumber(String number) { this.number = number; } // Getter public String getNumber() { return number; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PhoneNumber that = (PhoneNumber) o; return Objects.equals(number, that.number); } @Override public int hashCode() { return Objects.hash(number); } @Override public String toString() { return number; } }
Step 2: Complete the PhonebookEntry Class
You started this class, so let's finish it with getters and a toString() method for easy output:
public class PhonebookEntry { private Name name; private PhoneNumber phoneNumber; public PhonebookEntry(Name name, PhoneNumber phoneNumber) { this.name = name; this.phoneNumber = phoneNumber; } // Getters for comparison logic public Name getName() { return name; } public PhoneNumber getPhoneNumber() { return phoneNumber; } @Override public String toString() { return String.format("Name: %s, Phone Number: %s", name, phoneNumber); } }
Step 3: Build the Phonebook Class to Manage Entries
This class will handle the core logic: tracking previous entries, validating new entries, counting processed items, and storing valid entries.
import java.util.ArrayList; import java.util.List; public class Phonebook { private List<PhonebookEntry> validEntries; private PhonebookEntry previousEntry; private int processedEntryCount; public Phonebook() { validEntries = new ArrayList<>(); processedEntryCount = 0; } public void addEntry(PhonebookEntry newEntry) { processedEntryCount++; // Increment count immediately (processed regardless of validity) if (previousEntry != null) { Name prevName = previousEntry.getName(); PhoneNumber prevPhone = previousEntry.getPhoneNumber(); Name newName = newEntry.getName(); PhoneNumber newPhone = newEntry.getPhoneNumber(); // Case 1: Same name, different phone number if (prevName.equals(newName) && !prevPhone.equals(newPhone)) { System.out.println("⚠️ Warning: Adjacent entry has the same name but different phone number."); System.out.println("Outputting entry: " + newEntry); validEntries.add(newEntry); } // Case 2: Duplicate entry (same name and phone) else if (prevName.equals(newName) && prevPhone.equals(newPhone)) { System.out.println("❌ Error: Duplicate entry detected (same name and phone number)."); // Do NOT add duplicate to valid entries } // Case 3: Different name (or non-adjacent duplicate) else { System.out.println("Outputting entry: " + newEntry); validEntries.add(newEntry); } } else { // First entry, no previous to compare System.out.println("Outputting entry: " + newEntry); validEntries.add(newEntry); } // Update previous entry for next comparison previousEntry = newEntry; } // Getter for processed count public int getProcessedEntryCount() { return processedEntryCount; } // Getter for valid entries (returns a copy to prevent external modification) public List<PhonebookEntry> getValidEntries() { return new ArrayList<>(validEntries); } }
Step 4: Test the Implementation
Here's a sample main class to demonstrate how everything works:
public class Main { public static void main(String[] args) { Phonebook phonebook = new Phonebook(); // Create test entries PhonebookEntry entry1 = new PhonebookEntry(new Name("John", "Doe"), new PhoneNumber("123-456-7890")); PhonebookEntry entry2 = new PhonebookEntry(new Name("John", "Doe"), new PhoneNumber("987-654-3210")); PhonebookEntry entry3 = new PhonebookEntry(new Name("John", "Doe"), new PhoneNumber("987-654-3210")); PhonebookEntry entry4 = new PhonebookEntry(new Name("Jane", "Smith"), new PhoneNumber("555-555-5555")); // Add entries to the phonebook phonebook.addEntry(entry1); phonebook.addEntry(entry2); phonebook.addEntry(entry3); phonebook.addEntry(entry4); // Print results System.out.println("\n📊 Total processed entries: " + phonebook.getProcessedEntryCount()); System.out.println("✅ Valid entries stored: " + phonebook.getValidEntries().size()); } }
Expected Output
Outputting entry: Name: John Doe, Phone Number: 123-456-7890 ⚠️ Warning: Adjacent entry has the same name but different phone number. Outputting entry: Name: John Doe, Phone Number: 987-654-3210 ❌ Error: Duplicate entry detected (same name and phone number). Outputting entry: Name: Jane Smith, Phone Number: 555-555-5555 📊 Total processed entries: 4 ✅ Valid entries stored: 3
Key Notes
- Processed Count: Every call to
addEntry()increments the count, even if the entry is a duplicate (since it's still processed). - Equality Checks: The
equals()methods inNameandPhoneNumberare critical—without them, comparisons will check object references instead of actual values. - Adjacency Check: We only compare the new entry to the immediately previous one, as per your requirement.
- Immutability: It's a good idea to make
NameandPhoneNumberimmutable (no setters) to prevent unexpected changes after entry creation.
内容的提问来源于stack exchange,提问作者Ali Ahmad

