Java – prints elements from the array, commas between elements except the last word

I output elements from the array list. I want to add a comma between every word except the last word Now I do this:

for (String s : arrayListWords) {
         System.out.print(s + ",");
    }

As you know, it will print out the words: "one, two, three, four", and the problem is the last comma. How can I solve it? Enjoy all the answers!

Best wishes, Erica

Solution

If so, print your first word Then print the schema as a comma before printing the next element

if (arrayListWords.length >= 1) {
    System.out.print(arrayListWords[0]);
}

// note that i starts at 1,since we already printed the element at index 0
for (int i = 1; i < arrayListWords.length,i++) { 
     System.out.print("," + arrayListWords[i]);
}

With a list, you'd better use iterator

// assume String
Iterator<String> it = arrayListWords.iterator();
if (it.hasNext()) {
    System.out.print(it.next());
}
while (it.hasNext()) {
    System.out.print("," + it.next());
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>