I have written a program in Java 8 using BlueJ. There is just one function of type byte that accepts two String values and return 1 if the first word comes before the second in alphabetical order, and return -1 if the first word comes after the second in alphabetical order, and 0 if both are equivalent strings. I would welcome any suggestions on how to make my code faster and more readable.
public class Test
{
public static byte spaceshipAlphabetical (String str1, String str2)
{
int str1Length = str1.length();
int str2Length = str2.length();
int strLength;
if
(str1Length < str2Length)
{
str2 = str2.substring(0, str1Length);
strLength = str1.length();
}
else
{
str1 = str1.substring(0, str2Length);
strLength = str2.length();
}
str1 = str1.toUpperCase();
str2 = str2.toUpperCase();
char charStr1;
char charStr2;
int intChar1 = 0;
int intChar2 = 0;
for
(int i = 0; i < strLength; i++)
{
charStr1 = str1.charAt(i);
charStr2 = str2.charAt(i);
intChar1 = (int) charStr1;
intChar2 = (int) charStr2;
if
((intChar1 < intChar2) || (intChar2 < intChar1) || ((intChar2 == intChar1) && (i == (strLength - 1))))
{
break;
}
}
if
((intChar1 < intChar2) || ((intChar2 == intChar1) && (str1Length < str2Length)))
{
return 1;
}
else if
((intChar2 < intChar1) || ((intChar2 == intChar1) && (str2Length < str1Length)))
{
return -1;
}
else
{
return 0;
}
}
return str1.compare(str2);
, won't work? If so include the cases where it won't. \$\endgroup\$