user2805461
user2805461

Reputation: 1

separate integers in row with commas?

I feel like there is a simple way to do this but i'm trying to separate the numbers in this row with commas except the last one(being 20).

public class ForLoops
{
  public static void main(String[] args)
  {

    final int MAX = 21;
  for (int row = 1; row<MAX; row++)
    System.out.print(row);
}
}

instead of displaying 123456789101112(ect.) i need it to display 1,2,3,4,5,6,7,8,9,10,11,12(etc). any advise?

Upvotes: 0

Views: 118

Answers (2)

TheKojuEffect
TheKojuEffect

Reputation: 21081

for (int row = 1; row<MAX; row++) {
    System.out.print(row);
    if(row != MAX -1)
          System.out.print(",");

}

Upvotes: 1

hardmath
hardmath

Reputation: 8823

One of the integers needs to be printed in a special way, since we have one less comma than numbers to "print".

I suggest printing the first number without a comma, then looping through the remaining numbers printing a comma in front of the number.

When you finish the loop, you will probably want to print a newline.

Upvotes: 1

Related Questions