在java中增强for循环的最后一次迭代 [英] Last iteration of enhanced for loop in java

查看:2406
本文介绍了在java中增强for循环的最后一次迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法来确定循环是否最后一次迭代。我的代码看起来是这样的:

$ $ $ $ $ $ $ $ $> int [] array = {1,2,3 ...};
StringBuilder builder = new StringBuilder();

(int i:array)
{
builder.append(+ i);
if(!lastiteration)
builder.append(,);



$ b $ p
$ b现在的事情是我不想在最后加上逗号迭代。现在有一种方法来确定是否是最后一次迭代,或者我坚持使用for循环或使用一个外部计数器来跟踪。

解决方案

另一种选择是在追加i之前附加逗号,而不是在第一个第一个迭代中。 (请不要使用+ i ,顺便说一下,你并不想在这里串联,而且StringBuilder有一个非常好的append(int)重载。)

  int [] array = {1,2,3 ...}; 
StringBuilder builder = new StringBuilder();

(int i:array){
if(builder.length()!= 0){
builder.append(,);
}
builder.append(i);





$ b

好的一点是它可以和任何 Iterable - 你不能总是索引东西。 (当你真正使用StringBuilder的时候,添加逗号然后在最后删除它是一个很好的建议,但是它不适用于写入流的事情,但这可能是最好的方法。 )

Is there a way to determine if the loop is iterating for the last time. My code looks something like this:

int[] array = {1, 2, 3...};
StringBuilder builder = new StringBuilder();

for(int i : array)
{
    builder.append("" + i);
    if(!lastiteration)
        builder.append(",");
}

Now the thing is I don't want to append the comma in the last iteration. Now is there a way to determine if it is the last iteration or am I stuck with the for loop or using an external counter to keep track.

解决方案

Another alternative is to append the comma before you append i, just not on the first iteration. (Please don't use "" + i, by the way - you don't really want concatenation here, and StringBuilder has a perfectly good append(int) overload.)

int[] array = {1, 2, 3...};
StringBuilder builder = new StringBuilder();

for (int i : array) {
    if (builder.length() != 0) {
        builder.append(",");
    }
    builder.append(i);
}

The nice thing about this is that it will work with any Iterable - you can't always index things. (The "add the comma and then remove it at the end" is a nice suggestion when you're really using StringBuilder - but it doesn't work for things like writing to streams. It's possibly the best approach for this exact problem though.)

这篇关于在java中增强for循环的最后一次迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆