Avoid printing the last comma

前端 未结 13 523
无人及你
无人及你 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:36

    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));
    
    0 讨论(0)
  • 2020-12-03 15:37

    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(","));
    
    0 讨论(0)
  • 2020-12-03 15:43
    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 讨论(0)
  • 2020-12-03 15:44

    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));
    }
    
    0 讨论(0)
  • 2020-12-03 15:47
    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

    0 讨论(0)
  • 2020-12-03 15:47

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题