-1

Any suggestions for removing the comma in last element of the array when it prints?

public static void printList(String[] words, int count) {
    for (int i=0; i < count; i++) {
        System.out.print(words[i] + ",");
    }
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360

2 Answers2

2

One quick approach:

public static void printList(String[] words, int count) {
    for(int i = 0; i < count; i++) {
        System.out.print(words[i]);
        if(i != count-1) System.out.print(",");
    }
}
Villat
  • 1,455
  • 1
  • 16
  • 33
2

One way I like to handle this problem is to conditionally prepend a comma only for the second word onwards:

public static void printList(String[] words, int count) {
    for (int i=0; i < count; i++) {
        if (i > 0) System.out.print(",");
        System.out.print(words[i]);
    }
}

You could also build the output string you want, and then trim off the final comma:

StringBuilder sb = new StringBuilder();
for (int i=0; i < count; i++) {
    sb.append(words[i]).append(",");
}
String output = sb.toString().replaceAll(",$", "");
System.out.println(output);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360