You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 CountLines method consumes the Scanner stream, 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:

  • readContacts method: Replaces your CountLines method with a more robust approach that reads and parses contacts in one pass, using an ArrayList to avoid pre-defining array sizes (which is error-prone).
  • Try-with-resources: Automatically closes Scanner and PrintWriter to prevent resource leaks, so you don't need manual close() calls.
  • Clear sorting logic: Uses Java's Comparator.comparing() to create simple, readable sorters. For case-insensitive name sorting, replace Comparator.comparing(contact -> contact[0]) with Comparator.comparing(contact -> contact[0], String.CASE_INSENSITIVE_ORDER).
  • Proper output formatting: The Save method 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:01:11