静态方法,该方法采用字符串数组并返回整数

时间:2019-02-23 19:22:37

标签: java return

对于编程我还是很陌生,我正在尝试做一个小程序,在这里我编写了一个静态方法,该方法采用字符串数组并返回整数。从那里,我必须找到最小/最短字符串的索引位置,并返回该索引值。我完全迷失了这一点。我可以帮忙吗?

到目前为止我的代码...

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

4 个答案:

答案 0 :(得分:0)

您的代码实际上非常接近,但是-如果我正确理解您的任务-而不是实际的最小元素,则应该仅跟踪索引,因为这是最后要返回的内容。 / p>

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

答案 1 :(得分:0)

关注smallest方法。

public static void smallest(String[] month) {
    // since we have no knowledge about the array yet, lets
    // say that the currently known shortest string has
    // size = largest possible int value java can store 
    int min_length = Integer.MAX_INT, min_length_idx = -1;
    for (int i = 0; i < month.length; i++) {
        // is this current string a candidate for a new minimum?
        if (month[i].length() < min_length) {
            // if so, lets keep track of the length so that future
            // indices can be compared against it
            min_length = month[i].length();
            min_length_idx = i;
        }
    } 
    return min_length_idx;
}

然后,此方法还将涵盖数组中没有任何字符串(即空数组)的情况。

答案 2 :(得分:0)

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

注意:使用标准约定,其中变量名以小写字母开头。

答案 3 :(得分:0)

检查下面的代码,

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

}