开发者社区> 问答> 正文

Java在2D数组文本文件中按名称和数字排序

我正在尝试编写一个代码,以从.txt文件中读取联系人列表,按名称对其进行排序并输出(sortByNames.txt),然后按其电话号码对其进行排序,并输出一个不同的新文件(sortByNumbers.txt)

IE浏览器:

Michael - 0001234567
  Robert  - 0019234568
  Jacob   - 0011234567

需要通过数字变成这个:

Michael - 0001234567
  Jacob   - 0011234567
  Robert  - 0019234568

并按名称:

Jacob   - 0011234567
  Michael - 0001234567
  Robert  - 0019234568

这是我到目前为止的内容:

public static void Save(String[][] vals, File f) throws Exception {
    PrintWriter output = new PrintWriter(f);

    for (int rows = 0; rows < vals.length; rows++) {
        for (int cols = 0; cols < vals[rows].length; cols++) {
            output.print(vals[rows][cols]);
            output.print(" ");
        }
        output.println();
    }

    output.flush();
    output.close();
    return;
}

public static int CountLines(File f, Scanner reader) throws Exception {
    int lines = 0;
    while (reader.hasNextLine()) {
        String s = reader.nextLine();
        s = s.trim();
        if (s.length() == 0) {
            break;
        }
        lines++;
    }
    return lines;
}

public static void main(String[] args) throws Exception {
    File contacts = new File("Contacts.txt");
    Scanner reader = new Scanner(contacts);
    String[][] s = new String[CountLines(contacts, reader)][2];


    File name = new File("SortedByName.txt");

    File number = new File("SortedByNumber.txt");
}

如您所见,我已经弄清楚了有多少个联系人以及如何将数据保存到.txt文件中。

但是,我不知道如何按他们的数字甚至名字来排序。

有人可以帮我这个忙吗?在过去的几个小时中,我一直在绞尽脑汁,并且尝试进行搜索(但这使我无法理解的代码)。

如何按名称排序?如何按他们的号码排序?

非常感谢您的帮助!!

展开
收起
垚tutu 2019-11-29 23:07:27 828 0
1 条回答
写回答
取消 提交回答
  • #include

    使用Java 8很简单:

    Arrays.sort(s, (a, b) -> a[0].compareTo(b[0])); //sort by name
    Arrays.sort(s, (a, b) -> a[1].compareTo(b[1])); //sort by number
    
    

    希望它可以帮助您。编辑:您可以参考此代码。您可以用Java 8注释掉Sort来测试另一种方式

    public static void main(String... strings) {
    
        //Here we sort by number at 0 position
        String[][] s = new String[2][2];
        s[0][0] = "2";
        s[0][1] = "a";
        s[1][0] = "1";
        s[1][1] = "b";
        System.out.println("Before sorting: " + Arrays.deepToString(s));
        //Sort with java 8
        Arrays.sort(s, (a, b) -> a[0].compareTo(b[0]));
        //Sort without java 8
        for (int i = 0; i < s.length - 1; i++) {
            if (s[i][0].compareTo(s[i + 1][0]) > 0) {
                String[] temp = s[i + 1];
                s[i + 1] = s[i];
                s[i] = temp;
            }
        }
        System.out.println("After sorting: " + Arrays.deepToString(s));
    }
    
    

    输出: 排序之前:[[2,a],[1,b]]

    排序后:[[1,b],[2,a]]

    2019-11-29 23:08:01
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载