System.out.print(i+",");
I am trying to print a list of numbers using for loop and I am using the above line. But I get the output 1,2,3,
. I need 1,2,3
.
How can I do it?
System.out.print(i+",");
I am trying to print a list of numbers using for loop and I am using the above line. But I get the output 1,2,3,
. I need 1,2,3
.
How can I do it?
Many ways.
Use a StringBuilder
to make your string, then after the loop, if it is not empty, lop off the last character (sb.setLength(sb.length() - 1)
).
Use a boolean to track if this is the first time through the loop. If yes, just print the number. If not, print a comma, then the number. Set the boolean to false after.
Use string joining:
List<String> items = List.of("Hello", "World!");
System.out.println(String.join(", ", items));
Here's what I would do... use a StringBuilder and append to it inside of the loop like this.
Once the loop is finished, your output string will be ready and you can just remove the last character (which will be the comma)
StringBuilder sb = new StringBuilder();
for () {
sb.append(i+",");
}
// remove last comma
sb.setLength(sb.length() - 1);
System.out.println(sb.toString);
var buffer = new java.util.StringJoiner( "," );
for( var i = 1; i < endCriterion; ++i )
{
buffer.add( Integer.toString( i );
}
System.out.println( buffer.toString() );
For endCriterion == 3
this will print
1,2,3
to the console.
'java.util.StringJoiner' was added to the Java standard library with Java 8.