简体   繁体   English

想要为每个循环在Java中解决这个简单的问题

[英]want to solve this simple one in java for each loop

 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. values是浮点类型生成器的数组,每次调用时都是StringBuilder类型,我在values数组中有3个浮点值,我试图将'a'附加到builder和','在这里我得到的是(255,145,234,),但是我想要的是就像这样(255,145,234)我想省略最后一个逗号,您的帮助对我很有帮助,谢谢。

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: 或者,只需在循环退出后从StringBuilder截断最后一个字符:

builder.setLength(builder.length() - 1);

Maintain a count , and append "," until count is less than length of array. 保持一个count ,并附加","直到count小于数组的长度。

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

Use this. 用这个。 But there is no use of StringBuilder here.. 但是这里没有使用StringBuilder。

    ArrayList<String> val = new ArrayList<>();
    for(float f: values){
        val.add((int)(f*255)+"");
    }
    String s = String.join(", ", val);
    System.out.println(s);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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