Search code examples
javareturn

Static method that takes an array of strings and returns an integer


I am still pretty new to programming and I am trying to do this small program where I write a static method that takes an array of strings and returns an integer. From there I have to find the index position of the smallest/shortest string and return that index value. I am completely lost and struggling with this. Can I get some help?

My code so far...

public class test 
{

    public static void main(String [] args) 
    {
      String [] Month = {"July", "August", "September", "October"};
        smallest(Month);
        System.out.println("The shortest word is " + smallest(Month));
    }

    public static String smallest(String Month[]) 
    {
        String first = Month[0];
        for (int i = 1 ; i < Month.length ; i++) 
        {
            if (Month[i].length()<first.length())
             {
                first = Month[i];
            } 
        } 
        return first;
    }
}

Solution

  • Check the code below,

    public class Test {
        public static void main(String [] args) 
        {
          String [] month = {"July", "August", "September", "October"};
         //   smallest(Month);
            System.out.println("The shortest word index position is " + smallest(month));
        }
    
        public static int smallest(String Month[]) 
        {
            String first = Month[0];
            int position=0;
            for (int i = 1 ; i < Month.length ; i++) 
            {
                if (Month[i].length()<first.length())
                 {
                    first = Month[i];
                    position=i;
                } 
            } 
            return position;
        }
    
    }