Basically, the assignment is being an ass and doesn't want us to use an existing method to compare two strings alphabetically.
It should return 1 if the first string is "bigger" alphabetically than the second (in the sense that 'g' is bigger than 'a'), -1 if the second is bigger, or 0 if they are the same.
Lets say i have
String a = "Cows";
String b = "Horses";
The method should return -1.
My understanding is to use a for() loop to scan both a and b, using charAt(), but I have no idea how to implement this...
EDIT***
reading the answers I've come up with this.
int compared = 0;
for (int i = 0; i<s1.length() && i<s2.length(); i++){
int a = s1.charAt(i);
int b = s2.charAt(i);
if(a < b){
compared = -1;
}
else if(a > b){
compared = 1;
}
}
return compared;
The strings being compared all start with uppercase, so it shouldn't be a problem. However, when using the normal String.compareTo() and a bubblesort method that counts the number of times this method was called while sorting a predertermined string array, I get different results, which means something is obviously wrong.
For people viewing this and having the same problem, here's how the code works
int compared = 0;
//program assumes strings are equal
for (int i = 0; i<s1.length() && i<s2.length(); i++){
//for() loop goes on until the largest string
int a = s1.charAt(i);
int b = s2.charAt(i);
//convert char into int for comparison just in case
if(a < b){
compared = -1;
break;
//breaks at the first occurence of non equal characters
}
else if(a > b){
compared = 1;
break;
//same as above
}
}
return compared;
forloop andcharAtthing. Try that.