0

入力として文字列の配列を取得し、大文字のみの頭字語の配列を返すメソッドに取り組んでいます。

例えば:

[United Nations,  United Federation of Planets, null, , ignore me] -> [UN, UFP, null, , ]

何らかの理由で私のコードは何も返さず、null チェックが無効なコードであることも示しており、その理由がわかりません。

public static String[] convertStringsToAcronyms(String[] input) 
{
    int itemCount = input.length;
    String[] result = new String[itemCount];
    int k = 0;
    for (String words : input) {
        boolean checklowercase = words.toLowerCase().equals(words);

        if (checklowercase || (words == ""))
            result[k] = "";

        if (words == null)
            result[k] = null;

        String add = "";

        String[] ary = words.split("");
        for (String letter : ary) {
            char firstletter = letter.charAt(0);
            if (Character.isUpperCase(firstletter))
                add = add + firstletter;
        }

        result[k] = add;
        k++;
        add = "";

    }
    return result;

}
4

3 に答える 3

1

これにより、あなたが求めていることがもう少しエレガントになると思います。

public static sampleAcronymMethod()
{
    String[] arr =  {"United Nations",  "United Federation of Planets"};
    for (String element : arr) //go through all of our entries we wish to generate acronyms for
    {
    String[] splits =   element.split("[a-z]+");//remove all lowercase letters via regular expression
    String acronym = "";//start with an empty acronym

    for (String split : splits)//go through our uppercase letters for our current array entry in arr 
        acronym = acronym + split;//tack them together

    acronym = acronym.replaceAll("\\s","");//remove whitespace

   System.out.println("Acronym for " + element + " is " + acronym);
   }
}
于 2014-11-19T19:14:49.907 に答える
1

wordsnull チェックは、その前に変数にアクセスするため、デッド コードです。そのため、null のNullPointerException場合、null チェックの前に取得されます。

boolean checklowercase = words.toLowerCase().equals(words);
....
if (words == null) // this can never be true
    result[k] = null; // this is dead code
于 2014-11-19T18:58:01.763 に答える
0

Java 1.8 ではさらにエレガントに

    String[] i = new String[] {"United Nations",  "United Federation of Planets", null, "", "ignore me"};

    String[] array = Arrays.stream(i)
            .filter(it -> it != null && !it.isEmpty())
            .map(it -> it.split(" "))
            .map(words -> Arrays.stream(words)
                    .map(w -> w.substring(0, 1))
                    .filter(l -> l.toUpperCase().equals(l))
                    .collect(Collectors.joining()))
            .toArray(String[]::new);


    System.out.println(Arrays.toString(array));
于 2014-11-19T19:24:49.397 に答える