这个问题是我试图这样做,但我检查字符串长度的方法不起作用;我该怎么办才能修好它?
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; } }推荐答案
下面。 1.您使用 j< = animalNames.length; ?
你比较 animalNames [j + 1] ? - >错误索引超出数组
You compare animalNames[j + 1]? -> error index out of array
并在第一个条件返回时返回(animalNames [j]); - >错误值
and you return in the first if condition return (animalNames[j]); -> wrong value
好的,让我说清楚。 您可以在数组中找到最长的字符串。循环遍历数组,然后比较2个近元素,然后返回更大的元素。 使用您的代码,它将返回兔子。对吗?
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.
代码:
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];就是这样。