简体   繁体   中英

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 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 .

Note that it is better to use a StringBuilder to concatenate strings in a loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM