11

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 there is an easy solution to avoid printing the last comma. Much appreciated if somebody could help me out, this is driving me insane!!!

For example it loops from 1-10 // 1,2,3,4,5,6,7,8,9,10, < do not want this last comma

public static void atob(int a,int b)
{
    for(int i = a; i <= + b; i++) 
    {
        System.out.print(i + ",");
    }
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
OMGjava
  • 111
  • 1
  • 1
  • 3
  • 1
    You could use a While loop instead... or perhaps put it all into a single string and then use substring of the length -1 – radimpe Apr 03 '12 at 10:56
  • You could use some book http://stackoverflow.com/questions/1076580/recommend-an-algorithms-exercise-book – kommradHomer Apr 03 '12 at 10:59
  • Forgot to mention...i have to loop using for because the teacher said so...definitely not in a good spot. – OMGjava Apr 03 '12 at 11:01
  • @OMGjava mate i dont think sitting there and refreshing this page will serve the motivation of homework – kommradHomer Apr 03 '12 at 11:25
  • Yes, i wish it was that simple @kommradHomer – OMGjava Apr 03 '12 at 11:27
  • possible duplicate of [A quick and easy way to join array elements with a separator (the oposite of split) in Java](http://stackoverflow.com/questions/1978933/a-quick-and-easy-way-to-join-array-elements-with-a-separator-the-oposite-of-spl) – a'r Apr 03 '12 at 13:24

13 Answers13

13

I might get stoned to death for this answer

public static void atob(int a,int b) {
  if(a<=b) {
    System.out.println(a);
      for(int i = a+1;i<=b;i++) {
        System.out.println(","+i);
      }
    }
  }
}  
Aadi Droid
  • 1,689
  • 4
  • 22
  • 46
6

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));
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
5

Try this

public static void atob(int a,int b)
{
    for(int i = a; i < b; i++) 
    {
            System.out.print(i + ",");
    }
    System.out.print(b); 
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Farhan Ahmed
  • 342
  • 1
  • 8
4

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(","));
charlie
  • 1,478
  • 10
  • 20
3
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

Reg
  • 10,717
  • 6
  • 37
  • 54
1

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)

Jochem
  • 2,995
  • 16
  • 18
0

Use StringBuilder for it. use substring based index.

public class arraySort {
    public static void main(String[] args) {
        int a[] = { 2, 7, 5, 6, 9, 8, 4, 3, 1 };
        for (int i = 0; i < a.length; i++) {
            for (int j = i + 1; j < a.length; j++) {
                if (a[i] < a[j]) {
                    int temp;
                    temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
            }
        }

        System.out.print("Descending order:{");
        StringBuilder br = new StringBuilder();
        for (int i = 0; i < a.length; i++) {
            br.append(a[i] + ",");
        }
        System.out.print( br.substring(0, br.length()-1));
        System.out.println("}");

    }

}
Ravi Durairaj
  • 821
  • 7
  • 5
0
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(",");
            }
        }
}
0

Clunky solution, but hey - it works.

public static void atob(int a, int b){
 int count = 1;
  for(int i = a; i <= + b; i++) {
       System.out.print(i);
       if(count!=((b + 1) - a)) {
         System.out.print(", ");
         count++;
       }
    }
}

Alternatively, this works too.

public static void atob(int a, int b){
 int count = 0;
  for(int i = a; i <= + b; i++) {
    if(count > 0){
      System.out.print(", ");
    }
       System.out.print(i);
      count++;
   }
}
0

Found another simple way using regex:

String str = "abc, xyz, 123, ";
str = str.replaceAll(", $", "");
System.out.println(str);  // "abc, xyz, 123"
sameer_v
  • 414
  • 4
  • 11
0

You can simply use escape sequence for backspace(\b),outside the main loop,it will delete the last comma.

public static void atob(int a,int b)
        {
            for(int i = a; i <= + b; i++) 
            {
                    System.out.print(i + ",");
            }
            System.out.print("\b");
        }
Suyash
  • 39
  • 5
0

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);
    }
}
Mxyk
  • 10,678
  • 16
  • 57
  • 76
Anish Dasappan
  • 415
  • 2
  • 9
0

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));
}
Amos M. Carpenter
  • 4,848
  • 4
  • 42
  • 72