避免打印最后一个逗号

11
我正在尝试打印此循环,但不想要最后一个逗号。我已经在谷歌上搜索了一些关于此问题的内容,但似乎所有的方法都过于复杂,这个小问题应该有一个简单的解决方法。如果有人能帮我解决这个问题,我将不胜感激!例如,它从1到10循环 // 1,2,3,4,5,6,7,8,9,10,<不想要这个最后一个逗号>。
public static void atob(int a,int b)
{
    for(int i = a; i <= + b; i++) 
    {
        System.out.print(i + ",");
    }
}

1
你可以使用 While 循环代替... 或者将所有内容放入单个字符串中,然后使用长度-1的子字符串。 - radimpe
你可以使用一些书籍,例如http://stackoverflow.com/questions/1076580/recommend-an-algorithms-exercise-book。 - kommradHomer
忘了提一下...我必须使用for循环,因为老师这么说了...绝对不是一个好的情况。 - OMGjava
@OMGjava,伙计,我认为坐在那里不停地刷新页面并不能激发做作业的动力。 - kommradHomer
是的,我希望那很简单。@kommradHomer - OMGjava
可能是[A quick and easy way to join array elements with a separator (the oposite of split) in Java]的重复问题。(https://dev59.com/q3I-5IYBdhLWcg3wMFMf) - a'r
13个回答

13

我可能因为这个答案而被石头砸死

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);
      }
    }
  }
}  

我不明白为什么,这是我会做的方式。只需要在输出a之前对a进行范围检查即可。 - mcfinnigan

6
另一种方法是这样做。
String sep = "";
for(int i = a; i <= b; i++) {
    System.out.print(sep + i);
    sep = ",";
}

如果您正在使用 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));

5

试试这个

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

如果A大于B,则仍会打印A。 - Aadi Droid
最后一个打印语句中变量i超出了作用域,因此无法编译。 - Alderath
谢谢你让我对此有了更清晰的认识! - OMGjava

4

Java 8:

IntStream.rangeClosed(a, b)
         .collect(Collectors.joining(","));

如果你想执行交错操作:

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(","));

3
public static void atob(int a, int b) {
    if (a < b) {
        System.out.print(a);
        while (a < b) {
            a++;
            System.out.print("," + a);
        }
    }
}

当使用以下参数调用时:

atob(0,10);

将会得到以下输出:

0,1,2,3,4,5,6,7,8,9,10


atob(10,0) 将返回 10 作为输出,但不应打印任何内容。 - Jochem
谢谢你让我对此有了更清晰的认识! - OMGjava

1
一种通用的方法是区分第一个项目和其他所有项目。在第一次运行时,在 i 之前不打印逗号。之后,每次在 i 之前都打印逗号。
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;
    }
}

在这种特定情况下,使用三元运算符(http://en.wikipedia.org/wiki/Ternary_operation),您可以将其编写得非常紧凑:
public static void atob(int a,int b) {
    for(int i = a; i <= + b; i++) {
        System.out.print( i + ( i < b ? "," : "" ) ); 
    }
}

如果没有三元操作符,代码会变成这样(更易读,通常是一件好事):

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( "," );
    }
}

(请注意,+ b与b相同,因此您可以像其他人在答案中所做的那样替换它)


谢谢你让我对此有了更清晰的认识! - OMGjava

0
尝试:

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);
    }
}

谢谢你让我对此有了更清晰的看法! - OMGjava

0

稍作调整(方法名称、变量和逗号后的空格):

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));
}

谢谢你让我对此有了更清晰的认识! - OMGjava

0
你可以在主循环之外使用回退转义序列(\b),它将删除最后一个逗号。
public static void atob(int a,int b)
        {
            for(int i = a; i <= + b; i++) 
            {
                    System.out.print(i + ",");
            }
            System.out.print("\b");
        }

0
使用StringBuilder,基于子字符串索引。
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("}");

    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接