#java #массивы #функции
Задание звучит так:
You should implement the function String findLongestName(String []
names) which takes an array of Strings as an input containing a list
of names, and return the String that has the longest name.
To do so, try to follow these steps:
The first step is to calculate and store the length of the input
array, this is done using names.length; and store that in an integer
variable.
Then create a new String called longestName that will store
the longest name in the array of names, initialize it with the first
name in the array, that is names[0].
Next, you should create a for
loop that will compare every name in the array using names[i] against
the longestName. Only replace the longestName value if the names[i] is
longer .
Finally, return the longestName variable as the return value
of the function.
Вот мой код:
public String findLongestName(String [] names){
int size = names.length;
String longestName = names[0];
for (int i=0; i<=size; i++){
if (names[i].length()>longestName.length()){
longestName = names[i];
}
}
return longestName;
}
На попытку воспроизвести код выходит ошибка, что нужно что-то исправить (в прямом
смысле что-то, так как прохожу обучение языку на сайте). В чем проблема, не подскажите?
Принципиально не хочу смотреть ответ и пытаюсь сам понять в чем моя ошибка.
Заранее спасибо :)
Ответы
Ответ 1
Хм, даже не знаю, как ответить, чтобы Вам не смотреть ответ ). Тем не менее, иметь принципы в наше время - похвально. Индексы элементов в массиве изменяются от нуля до length минус один. for (int i = 0; i < size; i++) { ...
Комментариев нет:
Отправить комментарий