Avoid printing the last comma

前端 未结 13 597
无人及你
无人及你 2020-12-03 14:58

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

13条回答
  •  孤街浪徒
    2020-12-03 15:33

    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)

提交回复
热议问题