[英]Output values to be separated by commas and to exclude the last comma
I need my output to be separated by commas which it does, but I need the last comma excluded and also how would I rerun my program. 我需要用逗号分隔输出,但需要排除最后一个逗号以及如何重新运行程序。 I need to do this the simplest way as possible.
我需要以最简单的方式做到这一点。 This is what I have so far:
这是我到目前为止的内容:
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);
Loop around and put the result into a StringBuilder 循环并将结果放入StringBuilder
StringBuilder buf = new StringBuilder (" ");
while (num != -1) {
sum += num;
// u += num + ",";
buf.append (num).append (",");
num = input.nextInt();
}
then print all but the last 然后打印除最后一个以外的所有内容
System.out.println (buf.substring(0, buf.length () - 1));
if (u.endsWith(",")) {
u= u.substring(0, u.length() - 1);
}
or 要么
StringUtils.stripEnd(u, ",");
Replace 更换
u += num + ",";
with 与
u += (u.length() == 1 ? "" : ",") + num;
This only appends the comma if something has already been appended to u
. 仅当
u
附加了逗号时,才附加逗号。
Note that it is better to use a StringBuilder
to concatenate strings in a loop. 请注意,最好使用
StringBuilder
在循环中连接字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.