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
Yet another way to do this.
String sep = "";
for(int i = a; i <= b; i++) {
System.out.print(sep + i);
sep = ",";
}
if you are using a StringBuilder
StringBuilder sb = new StringBuilder();
for(int i = a; i <= b; i++)
sb.append(i).append(',');
System.out.println(sb.subString(0, sb.length()-1));
Java 8:
IntStream.rangeClosed(a, b)
.collect(Collectors.joining(","));
If you want to perform interleaving actions:
Java 8:
IntStream.rangeClosed(a, b)
.peek(System.out::print)
.limit(b - a) // [a:(b-1)]
.forEach(i -> System.out.print(","));
Java 9:
IntStream.rangeClosed(a, b)
.peek(System.out::print)
.takeWhile(i -> i < b) // [a:(b-1)]
.forEach(i -> System.out.print(","));
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(",");
}
}
}
With slight adjustments (method name, variables, and space after comma):
public static void printSequence(int start, int end) {
if (end < start) {
return; // or however you want to handle this case
}
if (end == start) {
System.out.print(start);
return;
}
StringBuilder sequence = new StringBuilder();
for (int i = start; i <= end; i++) {
sequence.append(i).append(", ");
}
// now simply print the sequence without the last ", "
System.out.print(sequence.substring(0, sequence.length() - 2));
}
public static void atob(int a, int b) {
if (a < b) {
System.out.print(a);
while (a < b) {
a++;
System.out.print("," + a);
}
}
}
When called with
atob(0,10);
Will give the output
0,1,2,3,4,5,6,7,8,9,10
Try:
public static void atob(int a, int b) {
if (b < a) {
final int temp = a;
a = b;
b = temp;
}
System.out.print(a++);
for (int i = a; i < b ; i ++ ) {
System.out.print("," + i);
}
}