在数组中除最后一个项目之外的项目之间插入分号

eul*_*ler 1 java loops

根据这篇文章中接受的答案,我有这个代码:

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

for (int i = 1; i < authors.length; i++) {
    System.out.print("; " + authors[i]);
}
Run Code Online (Sandbox Code Playgroud)

所以这个的输出是author1; author2; author3 如何将其改为author1; author2 & author3?如果只有2位作者,那么输出应该是author1 & author2.提前致谢.

JNY*_*ger 5

您只需要在循环中添加一个条件来处理最后一种情况:

for (int i = 1; i < authors.length; i++) {
    if(i == authors.length - 1)
        System.out.print("& " + authors[i]);
    else
        System.out.print("; " + authors[i]);
 }
Run Code Online (Sandbox Code Playgroud)