使用双打Java对数组进行排序

eva*_*ton 1 java arrays sorting comparator

我正在将文本文件读入2D数组.第一列(我正在排序的那个)几乎都是双打.大家都知道,它排序1.1 1.6 25.6 6.4,我该如何解决这个问题?

import java.io.*;
import java.util.*;

public class Sort {

    public static void main(final String[] args) throws FileNotFoundException {
        FileOutputStream out = new FileOutputStream("/Users/evanlivingston/2d.txt");
        PrintStream pout = new PrintStream(out);
        List<String[]> entries = new ArrayList<String[]>();
        Scanner sc = new Scanner(new File("/Users/evanlivingston/dists/0.txt"));
        while (sc.hasNext()) {
            entries.add(new String[] { sc.next(), sc.next()});
        }
        String[][] table = entries.toArray(new String[0][]);

        Arrays.sort(table, new Comparator<String[]>() {
            @Override
            public int compare(String[] s1, String[] s2) {
                String t1 = s1[0];
                String t2 = s2[0];
                return t1.compareTo(t2);               
            }      
        });
        pout.print(java.util.Arrays.deepToString(table));
        pout.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:
这是我更新的代码.它不会编译.

import java.io.*;
import java.util.*;

public class Sort {
    public static void main(String[] args) throws FileNotFoundException {
        FileOutputStream out = new FileOutputStream("/Users/evanlivingston/2d.txt");
        PrintStream pout = new PrintStream(out);
        List<Coords> coords = new ArrayList<Coords>();
        {
            Scanner sc = new Scanner(new File("/Users/evanlivingston/dists/0.txt"));
            while(sc.hasNextLine()) {
                String[] numstrs = sc.nextLine().split("\\s+");
            }
            String[][] table = coords.toArray(new String[0][]);

            Arrays.sort(table, new Comparator<Double[]>() {
                @Override
                public int compare(Double[] s1, Double[] s2) {
                    double a = Double.parseDouble(s1);
                    double b = Double.parseDouble(s2);
                    compare(a, b);
                }
            });
            pout.print(java.util.Arrays.deepToString(table));
            pout.close();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

cam*_*ckr 6

将双精度数存储在数组NOT Strings中.

因此,当您从文件中读取String时,将String转换为double.或者使用Scanner.nextDouble()方法为您执行此操作.

每次调用Comparator时,您都不希望转换字符串.