2
\$\begingroup\$

i get an array of authors from json response and i have to display authors name in TextView(android) in proper format like =>Viraj, Chetan and George R. R. Martin my code work fine, but it's a mess....

public class SeprateAuthors {
public static void main(String[] args) {
    String[] authors0 = {"a", "b"};
    String[] authors1 = {"a", "b", "c"};
    String[] authors2 = {"a", "b", "c","d"};
    String[] authors3 = {"a", "b", "c","d","e","f"};
    
    System.out.println(displayAuthors(authors0));
    System.out.println(displayAuthors(authors1));
    System.out.println(displayAuthors(authors2));
    System.out.println(displayAuthors(authors3));        
}
public static String displayAuthors(String[] authors) {
    StringBuilder stringBuilder = new StringBuilder();
    String stringAuthors="";
    String prefixComma = ", ";
    String prefixAnd = " and ";
    if ((authors != null) && (authors.length > 0)) {
        
        for (int i = 0; i < authors.length; i++) {
            if (i < authors.length - 2) {
                stringBuilder.append(authors[i]).append(prefixComma);
            } else {
                stringBuilder.append(authors[i]).append(prefixAnd);
            }
        }
        //  Java Remove extra Characters("and ") from String
        stringAuthors = stringBuilder.substring(0, stringBuilder.length() - 4);
    }
    return stringAuthors;
}

}

\$\endgroup\$
3
\$\begingroup\$

Welcome to Code Review, I have some hints about your code, starting from your main method:

public static void main(String[] args) {
    String[] authors0 = {"a", "b"};
    String[] authors1 = {"a", "b", "c"};
    String[] authors2 = {"a", "b", "c","d"};
    String[] authors3 = {"a", "b", "c","d","e","f"};
    
    System.out.println(displayAuthors(authors0));
    System.out.println(displayAuthors(authors1));
    System.out.println(displayAuthors(authors2));
    System.out.println(displayAuthors(authors3));        
}

You have defined several arrays forcing the multiple print , you can obtain the same result defining an 2d array storing arrays of different dimensions like below :

public static void main(String[] args) {
    String[][] authors = { {"a"},
                           {"a", "b"},
                           {"a", "b", "c"},
                           {"a", "b", "c","d"},
                           {"a", "b", "c","d","e","f"}};
    
    for (String[] row : authors) {
        System.out.println(displayAuthors(row));
    } 
}

About the print of the authors array you can distinguish three cases :

  1. array with zero elements : you will print the "" empty string.
  2. array with one element : you will print the unique element of the array.
  3. array with more than one element : you will print elements with ", " as separator except for the penultimate element and the last one that will be separated by "and".

You can rewrite your displayAuthors method in this way:

public static String displayAuthors(String[] authors) {
    if (authors == null) { return ""; }
        
    switch (authors.length) {
        case 0: return "";
        case 1: return authors[0];
        default: return helperDisplayAuthors(authors);
    }
}

I defined a new method called helperDisplayAuthors :

private static String helperDisplayAuthors(String[] authors) {
    final int length = authors.length;
    String result = "";
        
    for (int i = 0; i < length - 2; ++i) {
        result += authors[i] + ", ";
    }
        
    return String.format("%s%s and %s", result, 
            authors[length - 2], authors[length - 1]);
    }

}

The method String.format helps you to compose the final string. Here the code of your class:

public class SeparateAuthors {

    public static void main(String[] args) {

        String[][] authors = {{"a"},
                              {"a", "b"},
                              {"a", "b", "c"},
                              {"a", "b", "c", "d"},
                              {"a", "b", "c", "d", "e", "f"}};

        for (String[] row : authors) {
            System.out.println(displayAuthors(row));
        }
    }
    
    public static String displayAuthors(String[] authors) {
        if (authors == null) { return ""; }
        
        switch (authors.length) {
            case 0: return "";
            case 1: return authors[0];
            default: return helperDisplayAuthors(authors);
        }
    }

    private static String helperDisplayAuthors(String[] authors) {
        final int length = authors.length;
        String result = "";
        
        for (int i = 0; i < length - 2; ++i) {
            result += authors[i] + ", ";
        }
        
        return String.format("%s%s and %s", result, 
                authors[length - 2], authors[length - 1]);       
    }

}
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Are you sure that you want to use the inefficient String + String in your answer? \$\endgroup\$ – Roland Illig Aug 8 at 10:47
  • \$\begingroup\$ @RolandIllig Hello, I decided to use it to simplify how the string is built without use of StringBuilder even loosing in performance, probably not the best choice considering OP already used `StringBuilder' in the proposed approach. \$\endgroup\$ – dariosicily Aug 8 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.