I'm working on a homework assignment that requires me to compare two strings and determine if they're in alphabetical order.
I plan to write a method that will take two strings as arguments, (String a, String b) and return either 1, 0, or -1 (so, an int) signalling whether a > b, a < b, or otherwise (the 0 case).
For example, comparing ("boogie", "orange") would return a -1. since, boogie < orange.
My code so far is
public static int compare(String a, String b) {
for (int i = 0; i < a.length(); i++) {
for (int j = 0; j < b.length(); j++) {
char cha = a.charAt(i);
char chb = b.charAt(j);
if (cha < chb) {
return -1;
} else if (cha > chb) {
return 1;
}
}
return 0;
}
}
However, I am encountering numerous errors and cannot find fixes for the bugs. I'm also having difficulty finding a code for measuring if one word is longer than another (which affects alphabetical order) Can someone help me debug the code and point me in the right direction?
Many thanks in advance.
cha > chborcha < chbit returns. It will also return 0 right now if both words are identical.