The problem with this is that i tried to do it but my method to check the length of the string is not working; what can I do to fix it?
public static void main(String[] args) {
String[] animalNames = {"cat", "rabbit", "horse", "goat", "rooster", "ooooooooooooooo"};
String a= getLongestString(animalNames);
System.out.println(a);
}
public static String getLongestString(String []animalNames) {
// String animalNames[] = {"cat","chicken","horse","ooooooooo" };
int j = 0;
for (j = 0; j <= animalNames.length; j++) {
if (animalNames[j].length() > animalNames[j + 1].length()) {
return (animalNames[j]);
}
}
return null;
}
}
Here.
1. You use j<= animalNames.length;
?
You compare animalNames[j + 1]
? -> error index out of array
and you return in the first if condition return (animalNames[j]);
-> wrong value
Ok, let me make clear. You find the longest string in an array. You loop over the array then you compare 2 near elements, and then return the bigger one. With your code, it will return the rabbit. Right?
May be you confuse about the process flow. There is a simple way.
Code:
int index = 0;
int elementLength = array[0].length();
for(int i=1; i< array.length(); i++) {
if(array[i].length() > elementLength) {
index = i; elementLength = array[i].length();
}
}
return array[index];
that is it.