打印出数组中的元素,除了最后一个单词之外的元素之间用逗号分隔

Print out elements from an array with a comma between elements except the last word(打印出数组中的元素,除了最后一个单词之外的元素之间用逗号分隔)
本文介绍了打印出数组中的元素,除了最后一个单词之外的元素之间用逗号分隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在打印数组列表中的元素,并且希望在除最后一个单词之外的每个单词之间使用逗号.现在我正在这样做:

I am printing out elements from an array list and want to have a comma between each word except the last word. Right now I am doing it like this:

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

如你所见,它会打印出这样的单词:one,2,3,4, 而问题是最后一个逗号,我该如何解决?感谢所有答案!

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!

推荐答案

如果第一个单词存在,则单独打印.然后先将模式打印为逗号,然后是下一个元素.

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]);
}

使用 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());
}

这篇关于打印出数组中的元素,除了最后一个单词之外的元素之间用逗号分隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)