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] + ",");
}
}
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] + ",");
}
}
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(",");
}
}
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);