简体   繁体   中英

Why won't the array not sort alphabetically?

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]);

note: the file's content is as follows:

John
Rachel
Peter
Illyana
Erik
Jimmy
Dan
Ken
Guile
Barbara

The output is:

John
Rachel
Peter
Illyana
Erik
Jimmy
Dan
Ken
Guile
Barbara

John
Rachel
Peter
Illyana
Erik
Jimmy
Dan
Ken
Guile
Barbara

**I'm using OS X, can that be the source of the problem?

String name [] = {file};
You just initialize the array with one item in it , you just connected names with \\n ,seems like an array with multi items . You can initialize it like this :
String name[] = file.split("\\n");

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));
}

Use ArrayList instead of String so that you don't have to specify the size to initialize.

The above code is working. You can make modifications if required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM