I have an exercise in class where you take names from the user and output them alphabetically. I'm not allowed to use Array.sort() or compareTo(). I seem to have gotten it to work for the most part... Except for when I enter something like a aaa aa, it outputs it in the following order:
aaa
aa
a
I'd really like to be able to output it in this order instead:
a
aa
aaa
This is what I have so far:
public static void main(String args[]) throws IOException {
BufferedReader key =
new BufferedReader(new InputStreamReader(System.in));
System.out.println("Alphabetizing names\n");
System.out.println("Enter names separated by spaces:");
StringTokenizer names1 = new StringTokenizer(key.readLine());
int tokens = names1.countTokens();
String[] names2 = new String[tokens];
String y;
for (int a = 0; a < tokens; a++) {
names2[a] = names1.nextToken();
}
System.out.println("\nSorted names:");
for (int a = 0; a < tokens; a++) {
for (int b = a + 1; b < tokens; b++) {
if(alphabetize(names2[a], names2[b])) {
y = names2[a];
names2[a] = names2[b];
names2[b] = y;
}
}
}
for (int c = 0; c < tokens; c++) {
System.out.println(names2[c]);
}
}
static boolean alphabetize(String a, String b) {
for(int c = 0; ; c++) {
if((c == a.length()-1) && (c == b.length()-1)) {
return false;
}
if(c == a.length()-1) {
return true;
}
if(c == b.length()-1) {
return false;
}
if((a.toLowerCase().charAt(c) - b.toLowerCase().charAt(c)) > 0) {
return true;
}
}
}
Please help!! Thank you!