I\'m trying to print this loop without the last comma. I\'ve been Googling about this and from what i\'ve seen everything seems overcomplex for such a small problem. Surely
A general approach could be to make a distinction between the first item and all the others. The first run, no comma is printed BEFORE i. After that, a comma is printed before i, every time.
public static void atob(int a,int b) {
boolean first = true;
for(int i = a; i <= + b; i++) {
if ( first == false ) System.out.print(",");
System.out.print(i);
first = false;
}
}
In this specific case, using the ternary operator (http://en.wikipedia.org/wiki/Ternary_operation), you could write it as compact as:
public static void atob(int a,int b) {
for(int i = a; i <= + b; i++) {
System.out.print( i + ( i < b ? "," : "" ) );
}
}
Without ternary operation, this would look like this (and is more readable, which is often a good thing):
public static void atob(int a,int b) {
for(int i = a; i <= + b; i++) {
System.out.print( i );
if ( i < b ) System.out.print( "," );
}
}
(note that + b is the same as b, so you could replace that, as others have done in their answers)