簡體   English   中英

接受字符串數組並返回整數的靜態方法

[英]Static method that takes an array of strings and returns an integer

我對編程還是很陌生,我正在嘗試做這個小程序,我編寫了一個靜態方法,該方法接受一個字符串數組並返回一個整數。 從那里我必須找到最小/最短字符串的索引位置並返回該索引值。 我完全迷失了並為此而苦苦掙扎。 我能得到一些幫助嗎?

到目前為止我的代碼...

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

你的代碼實際上非常接近,但是——如果我正確理解你的任務——而不是實際的最小元素,你應該只跟蹤索引,因為這是你最終想要返回的。

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

專注於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;
}

此方法也將涵蓋數組中沒有任何字符串的情況,即空數組。

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

注意:使用標准約定,其中變量名稱以小寫字母開頭。

檢查下面的代碼,

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM