Avoid printing the last comma

前端 未结 13 590
无人及你
无人及你 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));
    

提交回复
热议问题