为什么不能按字母顺序对数组进行排序?

时间:2016-11-28 02:21:28

标签: java arrays sorting

public static void main(String[] args)
{
    String file = "";
    Scanner a = null;
    try
    {
        a = new Scanner(new File("names.txt"));
    }
    catch (FileNotFoundException e)
    {
        System.out.println("There was an error with your file");
        e.printStackTrace();
    }
    while(a.hasNextLine())
    {
        file = file +a.nextLine();
        file +="\n";
    }
    System.out.println(file);
    String name [] = {file};
    int i;
    for(i=0;i<name.length;i++)
    {
        for(int j=i+1;j<name.length;j++)
        {

            if(name[i].substring(0,1).compareTo(name[j].substring(0,1))<0)
            {
                String temp = name[i];
                name[i] = name[j];
                name[j] = temp;
            }
        }
    }
    for(i = 0;i < name.length;i++)
        System.out.println(name[i]);

注意:文件的内容如下:

John
Rachel
Peter
Illyana
Erik
Jimmy
Dan
Ken
Guile
Barbara

输出结果为:

John
Rachel
Peter
Illyana
Erik
Jimmy
Dan
Ken
Guile
Barbara

John
Rachel
Peter
Illyana
Erik
Jimmy
Dan
Ken
Guile
Barbara

**我使用OS X,这可能是问题的根源吗?

2 个答案:

答案 0 :(得分:1)

String name [] = {file};
您只需使用其中的一个项初始化数组,您只需将名称与\n连接,就像一个包含多个项目的数组。您可以像这样初始化它:
String name[] = file.split("\n");

答案 1 :(得分:1)

public static void main(String[] args) {
    String file = "";
    Scanner a = null;
    try {
        a = new Scanner(new File("E:\\names.txt"));
    } catch (FileNotFoundException e) {
        System.out.println("There was an error with your file");
        e.printStackTrace();
    }
    List<String> name;
    name = new ArrayList<String>();
    while (a.hasNextLine()) {
        file = a.nextLine();
        name.add(file);
        file += "\n";
    }
    System.out.println(file);
    int i;
    for (i = 0; i < name.size(); i++) {
        for (int j = i + 1; j < name.size(); j++) {

            if (name.get(i).substring(0, 1)
                    .compareTo(name.get(j).substring(0, 1)) < 0) {
                String temp = name.get(i);
                name.set(i, name.get(j));
                name.set(j, temp);
            }
        }
    }
    for (i = 0; i < name.size(); i++)
        System.out.println(name.get(i));
}

使用ArrayList而不是String,这样就不必指定要初始化的大小。

以上代码正常运行。如果需要,您可以进行修改。