我从数组列表中输出元素,我想在除了最后一个单词之外的每个单词之间加一个逗号.现在我这样做:
for (String s : arrayListWords) {
System.out.print(s + ",");
}
如你所知,它将打印出这样的词:“一,二,三,四”
而问题是最后一个逗号,我该如何解决呢?所有答案欣赏!
最好的祝福,
埃里卡
解决方法
如果存在,打印自己的第一个单词.然后先将模式打印为逗号,然后再打印下一个元素.
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]);
}
有了List,你最好使用Iterator
// assume String
Iterator<String> it = arrayListWords.iterator();
if (it.hasNext()) {
System.out.print(it.next());
}
while (it.hasNext()) {
System.out.print("," + it.next());
}
