Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Complete the skeleton below for the method named longest that takes an array of

ID: 3804326 • Letter: C

Question

Complete the skeleton below for the method named longest that takes an array of Strings as input and returns the longest String in the array to the calling program. For example, if the array has the values {"The", "Brown", "Fox"} then the method will return the value "Brown". In the case of ties your code can return ANY String with the longest length. For example if the array has the values {"The", "Quick", "Brown", "Fox"} you may return either "Brown" or "Quick". You may assume that the arrays passed to the method will have a length of at least 1.

private static String longest(String[] array) { // your code goes here

Explanation / Answer

    private static String longest(String[] array) {
       int maxLength = 0;
       int maxIndex = -1;
       for (int i=0; i<array.length; i++) {
           if (maxLength < array[i].length()) {
               maxLength = array[i].length();
               maxIndex = i;
           }
       }
       if (maxIndex == -1) {
           return null;
       }
       return array[maxIndex];
   }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote