输出值以逗号分隔并排除最后一个逗号

Output values to be separated by commas and to exclude the last comma

我需要我的输出用逗号分隔,但我需要排除最后一个逗号,以及我将如何重新运行我的程序。我需要尽可能以最简单的方式做到这一点。这是我目前所拥有的:

System.out.print("Enter numbers (-1 to end):");

  int num = input.nextInt();      
  int sum = 0;
  String u= " ";

  while (num != -1) {
    sum += num;
    u += num + ",";
    num =  input.nextInt();
  }
System.out.println("Entered Numbers: " + u);

System.out.println("The Sum: " + sum);

替换

u += num + ",";

u += (u.length() == 1 ? "" : ",") + num;

这只会在 u.

后附加逗号

请注意,最好使用 StringBuilder 在循环中连接字符串。

循环并将结果放入 StringBuilder

StringBuilder buf = new StringBuilder  (" ");
while (num != -1) {
  sum += num;
//  u += num + ",";

  buf.append (num).append (",");
  num =  input.nextInt();
  }

然后打印除最后一个以外的所有内容

  System.out.println (buf.substring(0, buf.length () - 1));
if (u.endsWith(",")) {
  u= u.substring(0, u.length() - 1);
}

StringUtils.stripEnd(u, ",");