Reputation: 283
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.
Upvotes: 2
Views: 612
Reputation: 1
You can compare two char by using '-' operator rather than the '>'. For example below.
public static int compare(String a, String b) {
return a.charAt(0) - b.charAt(0);
}
In your case, something like this.
public static int compare(char cha, char chb) {
if (cha-chb < 0) {
return -1;
} else if(chb - cha > 0){
return 1;
} else if(chb - cha == 0){
return 0;
}
return 0;
}
Upvotes: -1
Reputation: 394126
You don't need a nestd loop, since you don't want to compare every character of one String to every character of the other String.
You only need a single loop:
public static int compare(String a, String b)
{
int len = Math.min (a.length(),b.length());
for (int i = 0; i<len; i++) {
char cha = a.charAt(i);
char chb = b.charAt(i);
if (cha < chb) {
return -1;
} else if (cha > chb) {
return 1;
}
}
if (a.length() < b.length())
return -1;
else if (a.length() > b.length())
return 1;
else
return 0;
}
As for handling Strings of different lengths, if you find that the shorter of the 2 Strings is equal to the prefix of the longer String, you return -1 if a is the shorter String and 1 if b is shorter (since the shorter String should come before the longer one).
Upvotes: 2