a.s a.s - 12 days ago 7
Java Question

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?

Answer

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