-2
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?

Roddy of the Frozen Peas
  • 14,380
  • 9
  • 49
  • 99
Nithin Gowda
  • 129
  • 1
  • 10
  • 3
    Please add your code. – Jayan Mar 13 '20 at 15:51
  • 1
    Does this answer your question? [The simplest way to comma-delimit a list?](https://stackoverflow.com/questions/668952/the-simplest-way-to-comma-delimit-a-list) – agillgilla Mar 13 '20 at 15:54
  • Could also do a conditional. `System.out.print(i < maxValue - 1 ? i + ", " : i);` – Tim Hunter Mar 13 '20 at 15:55
  • Add more Context Please. Du you use an Array? Whats the way you create i? Oder you use a list you can use an iterator und checkt the hasNext method to Stop printing the last comma – FishingIsLife Mar 13 '20 at 15:56

4 Answers4

2

Many ways.

  1. 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)).

  2. 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.

  3. Use string joining:

List<String> items = List.of("Hello", "World!");
System.out.println(String.join(", ", items));
rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
1

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);
rhowell
  • 1,165
  • 8
  • 21
1

Well there's standard library's method for it:

String.join(", ", s);
Dmitry Pisklov
  • 1,196
  • 1
  • 6
  • 16
0
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.

tquadrat
  • 3,033
  • 1
  • 16
  • 29