通讯录程序:首次输入存文件夹+重复号码校验问题求助
Hey there! Let's tackle your two requirements step by step, focusing on fixing that duplicate contact validation issue first since it's causing unexpected behavior.
需求1:首次输入内容保存至文件夹后引用
To make sure your first input gets saved to a folder before being referenced later, follow these straightforward steps:
- Create a dedicated folder for contact data if it doesn't exist. This keeps your data organized and avoids file-not-found errors.
- Save initial input to a file when the program first runs. Use a simple text file (e.g.,
contacts_data/contacts.txt) with a format likeName,PhoneNumberper line for easy reading/writing. - Load data from the file on program startup so all subsequent operations reference the saved entries instead of starting from scratch.
Here's a quick code snippet to handle folder creation and initial load:
import java.nio.file.Files; import java.nio.file.Paths; import java.io.IOException; public class ContactManager { public static void main(String[] args) { // Create contacts folder if it doesn't exist try { Files.createDirectories(Paths.get("contacts_data")); System.out.println("Contacts folder initialized successfully."); } catch (IOException e) { System.out.println("Failed to create contacts folder: " + e.getMessage()); } // Load existing contacts from file here (we'll tie this into validation below) } }
需求2:修复联系人重复条目校验逻辑
The root issue with your current validation is likely that you're either not checking against existing entries properly, or saving the entry before validating it. Let's fix this by using a HashSet to track unique phone numbers and adding a loop to enforce valid, non-duplicate inputs.
Step 1: Track Existing Numbers
First, add a static set to store phone numbers—this lets us check for duplicates in constant time. We'll also load existing numbers from our saved file on startup:
import java.util.HashSet; import java.util.Set; import java.nio.file.Files; import java.nio.file.Paths; import java.io.IOException; public class ContactManager { // Store existing phone numbers to check duplicates private static Set<String> existingNumbers = new HashSet<>(); static { // Load existing numbers from file when the program starts try { if (Files.exists(Paths.get("contacts_data/contacts.txt"))) { Files.lines(Paths.get("contacts_data/contacts.txt")) .map(line -> line.split(",")[1].trim()) // Extract phone number from each line .forEach(existingNumbers::add); } } catch (IOException e) { System.out.println("Warning: Could not load existing contacts. Starting fresh."); } } // Rest of your code... }
Step 2: Validate Input Before Saving
Replace your current number input logic with this loop that enforces valid, non-duplicate entries:
import java.util.Scanner; import java.nio.file.Files; import java.nio.file.Paths; import java.io.BufferedWriter; import java.nio.file.StandardOpenOption; import java.io.IOException; public class ContactManager { // ... existing code ... public static void addContact() { Scanner scanner = new Scanner(System.in); String number; // Loop until we get a valid, non-duplicate number while (true) { System.out.print("Enter Number: "); number = scanner.nextLine().trim(); // Optional: Validate number format (e.g., only digits) if (!number.matches("\\d+")) { System.out.println("Invalid number! Please enter only digits."); continue; } // Check if number already exists if (existingNumbers.contains(number)) { System.out.println("Oops! This number is already in your contacts. Try a different one."); } else { break; // Exit loop when we have a valid, unique number } } // Get contact name System.out.print("Enter Name: "); String name = scanner.nextLine().trim(); // Save contact to file try (BufferedWriter writer = Files.newBufferedWriter( Paths.get("contacts_data/contacts.txt"), StandardOpenOption.APPEND, StandardOpenOption.CREATE)) { writer.write(name + "," + number); writer.newLine(); existingNumbers.add(number); // Update our set with the new number System.out.println("Contact added successfully!"); } catch (IOException e) { System.out.println("Failed to save contact: " + e.getMessage()); } } public static void main(String[] args) { // Initialize folder try { Files.createDirectories(Paths.get("contacts_data")); } catch (IOException e) { System.out.println("Failed to create contacts folder: " + e.getMessage()); } // Add a contact example addContact(); } }
Why This Works:
HashSetfor fast lookups: Checking if a number exists is O(1), so even with lots of contacts, validation stays quick.- Loop until valid input: Users can't proceed until they enter a number that's both formatted correctly and not already in the contacts.
- Sync file and memory: After saving to the file, we update our
existingNumbersset so future checks include the new entry.
内容的提问来源于stack exchange,提问作者Henri Wurm

