Java实现联系人按姓名和手机号排序并输出文件求助
Solution for Sorting Contacts by Name and Phone Number
Hey there! Let's fix your sorting issue and get your contact list sorted properly. First, let's break down the gaps in your current code:
- Your
CountLinesmethod consumes theScannerstream, so you can't read the actual contact data afterward - You haven't added logic to parse each line into name-number pairs
- Missing comparator logic to sort contacts by name or phone number
Here's the revised, complete code that addresses all these points:
import java.io.File; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Scanner; public class ContactSorter { // Updated save method to preserve the original "Name - Number" format public static void Save(List<String[]> contacts, File f) throws Exception { // Use try-with-resources to auto-close the writer and avoid leaks try (PrintWriter output = new PrintWriter(f)) { for (String[] contact : contacts) { output.println(contact[0] + " - " + contact[1]); } } } // Read and parse contacts from file in one go (replaces your CountLines method) public static List<String[]> readContacts(File contactsFile) throws Exception { List<String[]> contacts = new ArrayList<>(); try (Scanner reader = new Scanner(contactsFile)) { while (reader.hasNextLine()) { String line = reader.nextLine().trim(); if (line.isEmpty()) { continue; // Skip empty lines instead of stopping entirely } // Split each line using " - " as the delimiter to get name and number String[] parts = line.split(" - "); if (parts.length == 2) { // Ensure the line is in valid format contacts.add(new String[]{parts[0].trim(), parts[1].trim()}); } } } return contacts; } public static void main(String[] args) throws Exception { File contactsFile = new File("Contacts.txt"); File sortedByNameFile = new File("SortedByName.txt"); File sortedByNumberFile = new File("SortedByNumber.txt"); // Step 1: Read all contacts from the input file List<String[]> contacts = readContacts(contactsFile); System.out.println("Total contacts found: " + contacts.size()); // Step 2: Sort contacts by name (use String.CASE_INSENSITIVE_ORDER for case-agnostic sorting) List<String[]> sortedByName = new ArrayList<>(contacts); sortedByName.sort(Comparator.comparing(contact -> contact[0])); // Step 3: Sort contacts by phone number (string comparison works here since numbers are fixed-length) List<String[]> sortedByNumber = new ArrayList<>(contacts); sortedByNumber.sort(Comparator.comparing(contact -> contact[1])); // Step 4: Save sorted lists to their respective files Save(sortedByName, sortedByNameFile); Save(sortedByNumber, sortedByNumberFile); System.out.println("Sorting done! Check SortedByName.txt and SortedByNumber.txt for results."); } }
Key improvements explained:
readContactsmethod: Replaces yourCountLinesmethod with a more robust approach that reads and parses contacts in one pass, using anArrayListto avoid pre-defining array sizes (which is error-prone).- Try-with-resources: Automatically closes
ScannerandPrintWriterto prevent resource leaks, so you don't need manualclose()calls. - Clear sorting logic: Uses Java's
Comparator.comparing()to create simple, readable sorters. For case-insensitive name sorting, replaceComparator.comparing(contact -> contact[0])withComparator.comparing(contact -> contact[0], String.CASE_INSENSITIVE_ORDER). - Proper output formatting: The
Savemethod now writes lines in the original "Name - Number" format instead of space-separated values.
Testing this with your sample data:
Original data:
Michael - 0001234567
Robert - 0019234568
Jacob - 0011234567
- Sorted by name: Jacob - 0011234567, Michael - 0001234567, Robert - 0019234568 (matches your expected result)
- Sorted by phone number: Michael - 0001234567, Jacob - 0011234567, Robert - 0019234568 (also matches your expected result)
内容的提问来源于stack exchange,提问作者MrOutside
相关产品推荐
相关产品推荐

