0
 for (float f: values)
    {
        int a=(int) (f*255);
        builder.append(' ')
               .append(a+",");
    }

values is array of float type builder is StringBuilder type on every call I have 3 float values in values array I am trying to append 'a' to builder and ',' here what I am getting is like (255,145,234,) but what I want is like this(255,145,234) I want to omit the last comma your Help is quite helpful to me Thanks.

android
  • 89
  • 11
  • 1
    possible duplicate of [Remove last character of a StringBuilder?](http://stackoverflow.com/questions/3395286/remove-last-character-of-a-stringbuilder) – haley Dec 23 '14 at 04:22

3 Answers3

3

Try this:

String delimiter = "";
for (float f: values)
    {
        builder.append(delimiter)
        delimiter = ", ";
        int a=(int) (f*255);
        builder.append(a);
    }

Alternatively, simply chop off the last character from the StringBuilder after the loop exits:

builder.setLength(builder.length() - 1);
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

Maintain a count, and append "," until count is less than length of array.

public static void main(String[] args) {

        float[] values = { 255, 145, 234 };
        StringBuilder builder = new StringBuilder();
        int count = 0;

        for (float f : values) {
            count++;
            int a = (int) (f * 255);
            builder.append(' ').append(a);
            if (count < values.length) {
                builder.append(",");
            }
        }
        System.out.println(builder.toString());
    }

output

 65025, 36975, 59670
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
0

Use this. But there is no use of StringBuilder here..

    ArrayList<String> val = new ArrayList<>();
    for(float f: values){
        val.add((int)(f*255)+"");
    }
    String s = String.join(", ", val);
    System.out.println(s);
Ramesh-X
  • 4,853
  • 6
  • 46
  • 67