我正在打印 ArrayList
中的元素,并且希望在除最后一个单词之外的每个单词之后有一个逗号。
现在,我正在这样做:
for (String s : arrayListWords) {
System.out.print(s + ", ");
}
它打印出这样的单词:
one, two, three, four,
问题是最后一个逗号。我该如何解决?
最佳答案
如果存在,则单独打印第一个单词。然后先将模式打印为逗号,然后是下一个元素。
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());
}
https://stackoverflow.com/questions/18279622/