Returns the element number of the longest string in the array

I am trying to get the longest method to take a user-entered array of strings, and then return the element number of the longest string in this array. I brought it to such an extent that I was able to return the number of characters in the longest line, but I do not believe that this will work for what I need. My problem is that I get incompatible type errors all the time trying to figure this out. I still do not understand all the data type information with strings. It confuses me as I return to the array, but the array has strings. The main method is ok, I'm stuck on ???? 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; 
}
+3
source share
4 answers
    for (int i = 0; i < values.length; i++)
    {
        if (values[i].length() > largest)
        {
            largest = values[i].length();
            index = i;
        }
    }
    return index;

: int i 0 - 0.

main, System.out.println("Longest: " + responseArr[highest]); ..

+3

:

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;
}
+3

You need to save two things in your method longestS: the longest so far and the index of the longest array. Also keep in mind that array indices start at 0 in Java. A for loop initialized with help int i = 1will actually start at the second index.

+2
source

My decision:

public class JavaApplication3
{
    public static void main(String[] args)
    {
        String[] big={"one","two","three"};
        String bigstring=null;
        int maxlength=0;
        for(String max:big)
        {
            if(maxlength<max.length())
            {
                maxlength=max.length();
                bigstring=max;
            }
        }
        System.out.println(bigstring);
    }
}
+1
source

Source: https://habr.com/ru/post/1749869/


All Articles