This is the question: Write a static method called longestString that accepts an
ID: 3666707 • Letter: T
Question
This is the question:
Write a static method called longestString that accepts an array of strings and returns an array of String with two elements. The first element will be the longest String(the last occurance in the case of a tie) and the second element will be the index that it was found at(expressed as a string) . If the list is null return a null.
This is what I have started:
public static int isLongest(String[] data)
{
int longString = 0;
for(String s : data)
{
if (s.length() > longString)
longString = s.length();
}
return longString;
}
Explanation / Answer
public static String[] isLongest(String[] data)
{
if(data == null)
return null;
int indexOfLongString = -1;
String longString ="";
for(int i = 0 ; i<data.length; i++)
{
if (data[i].length() >= longString.length())
longString = data[i];
indexOfLongString = i;
}
String result[] = {longString,String.valueOf(indexOfLongString)};
return result;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.