Java 如何防止在这个增强的forloop中打印逗号
输出会在数组的最后一个数字后继续打印逗号。如果您不想打印最后一个逗号,例如,使用[5,10,247]数组,则要将其作为Java 如何防止在这个增强的forloop中打印逗号,java,for-loop,Java,For Loop,输出会在数组的最后一个数字后继续打印逗号。如果您不想打印最后一个逗号,例如,使用[5,10,247]数组,则要将其作为 for ( int i : array ) { System.out.print(i + ", "); } 你可以把它放在 5, 10, 27 逗号正在打印,因为有行 boolean first = true; for ( int i : array ){ // If we have items printed add comma before printin
for ( int i : array ) {
System.out.print(i + ", ");
}
你可以把它放在
5, 10, 27
逗号正在打印,因为有行
boolean first = true;
for ( int i : array ){
// If we have items printed add comma before printing the next one
if (!first)
System.out.print(", ")
first = false;
System.out.print(i);
}
如果你想要一个空格而不是逗号,试试看
System.out.print(i +", ");
或者干脆试试
System.out.print(i+" ");
这将在打印i的值后自动更改行将其更改为以下内容:
System.out.println(i);
因此,除了第一次,每次都以逗号开头。你可以试试
for(int i=0; i<array.length; i++) {
if (i == 0) {
System.out.print(array[i])
} else {
System.out.print("," + array[i])
}
}
使用这样的代码
int arrayLength = array.length;
for ( int i : array){
if( i == arrayLength - 1 )
System.out.print(i);
else
System.out.print(i + ", ");
}
旁注:这些问题/古怪的问题,作为学习的一部分,你需要弄清楚 最简单的方法是:
int count = 0; //flag to know which index you are looping through
for (int i : array) {
count++;//increment it every-time
if (count == 1) { //This is the only time when you do not want the ',' to be printed
System.out.print(i);
} else {
System.out.print(","); //can do (","+i)
System.out.print(i);
}
}
但是,如果要使用增强的for循环执行此操作:
System.out.print(
Arrays.stream(array).mapToObj(Integer::toString).collect(Collectors.joining(", ")));
如何使用另一种类型的循环来解决这个问题?使用带有索引的旧式变体?您希望在末尾有一个字符串是什么?如果这是一个字符串数组,并且您使用的是Java 8,那么您最好使用System.out.printlnString.join,,array,而不是整个循环。既可读又解决了逗号问题。它将不起作用,因为i==arrayLength奇怪的条件值i不是数组的索引,而是实际值。这是错误的。对于int i:array使我获取数组内容的值。数组可能不是整数数组,并且它永远不会接受当前正在检查的数组位置的值,除非位置和值相同。您不理解他的问题现在应该更清楚我想显示的内容。使用标准for-loop。感谢您提供此代码段,这可能会提供一些即时的帮助。通过说明为什么这是一个很好的解决问题的方法,正确地解释它的教育价值,并将使它对未来有类似但不完全相同问题的读者更有用。请在回答中添加解释,并说明适用的限制和假设。
System.out.print(
Arrays.stream(array).mapToObj(Integer::toString).collect(Collectors.joining(", ")));
String delim = "";
for (int i : array) {
System.out.print(delim);
System.out.print(i);
delim = ", ";
}