用最后一个单词之外的元素之间的逗号打印出数组中的元素 [英] Print out elements from an array with a comma between elements except the last word
问题描述
我打印出数组列表中的元素,除了最后一个字之外,我希望在每个单词之间有一个逗号。现在我正在做这样的事情: 祝好,
$ p $ for(String s:arrayListWords){
System.out.print s +,);
$ b你知道它会打印出如下的单词:one,two ,三,四,
和问题是最后一个逗号,我该如何解决?所有答案赞赏!
Erica
if(arrayListWords.length> = 1){
System.out.print(arrayListWords [0]);
}
//注意我从1开始,因为我们已经在index 0
处打印了元素(int i = 1; i< arrayListWords.length,i ++ ){
System.out.print(,+ arrayListWords [i]);
$ b $ List
,你最好使用 Iterator
//假定String
Iterator< String> it = arrayListWords.iterator();
if(it.hasNext()){
System.out.print(it.next()); (it.hasNext()){
System.out.print(,+ it.next());
while
}
I am printing out elements from a array list, I want to have a comma between each word except the last word. Right now I am doing like this:
for (String s : arrayListWords) {
System.out.print(s + ", ");
}
As you understand it will print out the words like this: "one, two, three, four,"
and the problem is the last comma, how do I solve this? All answers appreciated!
Best regards,
Erica
解决方案 Print the first word on its own if it exists. Then print the pattern as comma first, then 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're better off using an Iterator
// assume String
Iterator<String> it = arrayListWords.iterator();
if (it.hasNext()) {
System.out.print(it.next());
}
while (it.hasNext()) {
System.out.print(", " + it.next());
}
这篇关于用最后一个单词之外的元素之间的逗号打印出数组中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!