views:

94

answers:

3

Hoookay, so. I'm trying to get the longestS method to take the user-inputted array of strings, then return the element number of the longest string in that array. I got it to the point where I was able to return the number of chars in the longest string, but I don't believe that will work for what I need. My problem is that I keep getting incompatible type errors when trying to figure this out. I don't understand the whole data type thing with strings yet. It's confusing me how I go about return a number of the array yet the array is of strings. The main method is fine, I got stuck on the ???? part.

{
public static void main(String [] args) 
  {
    Scanner inp = new Scanner( System.in );
    String [] responseArr= new String[4];

 for (int i=0; i<4; i++)
  {
     System.out.println("Enter string "+(i+1));
     responseArr[i] = inp.nextLine();
  }
 int highest=longestS(responseArr);

}

public static int longestS(String[] values)
    {     
   int largest=0

    for( int i = 1; i < values.length; i++ )
     {
        if ( ?????          )





     }


   return largest;  
}

}
+2  A: 
    for (int i = 0; i < values.length; i++)
    {
        if (values[i].length() > largest)
        {
            largest = values[i].length();
            index = i;
        }
    }
    return index;

Note: initialize the int i with 0 - array index is 0-based.

Back in your main, you could then do System.out.println("Longest: " + responseArr[highest]); etc.

Lauri Lehtinen
+2  A: 

You will want to store two things in your longestS method: the largest length so far, and the array index of the largest length. Also keep in mind that array indices start at 0 in Java. A for loop initialised with int i = 1 is actually going to start at the second index.

Ash
+2  A: 

Here's how I'd write it:

public static int findIndexOfLongestString(String[] values)
{     
   int index = -1;

   if ((values != null) && (values.length > 0))
   {
       index = 0;
       String longest = values[0];
       for (int i = 1; i < values.length; ++i)
       {
          if (values[i].length() > longest.length())
          {
             longest = values[i];
             index = i;
          }
       }
   }

   return index;
}
duffymo
+1, though you might want to fix the redeclaration of index.
Mark Peters