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