有没有一种方法来实现使用最终变量的循环? 我的意思是一个循环,当你不允许在初始化后改变任何东西时,它会运行指定的迭代次数!使用最终变量实现循环
2
A
回答
8
是递归允许的,或者你从字面上需要一个循环构造像for
或while
?如果你可以使用递归的话:
void loop(final int n) {
if (n == 0) {
return;
} else {
System.out.println("Count: " + n);
loop(n-1);
}
}
+0
这很有趣:) – 2013-03-21 18:40:51
0
事情是这样的 -
final int max = 5;
for(int i=0; i<max; i++) {}
或者另一个有趣的单
final boolean flag = true;
while(flag) {
// keep doing your stuff and break after certain point
}
一个更多 -
List<String> list = ......
for(final Iterator iterator = list.iterator(); iterator.hasNext();) {
}
+0
不确定'i'或'flag'是否不制动规则“初始化后你不允许改变任何东西” – Pshemo 2013-03-21 18:37:26
0
创建一个数组,其大小为所需的迭代次数,然后在for-each循环使用它:
public class Test {
public static void main(String[] args) {
final int N = 20;
final int[] control = new int[N];
for(final int i : control){
System.out.println(i);
}
}
}
这里的诀窍是,迭代索引由编译器生成,作为增强for语句的一部分,不使用任何用户声明的变量。
1
的一种方式是创建表示任意范围的Iterable<Integer>
类(而实际上不必所有的值存储在一个列表):
public static class FixedIntRange implements Iterable<Integer> {
private final int min;
private final int max;
public FixedIntRange(final int min, final int max) {
this.min = min;
this.max = max;
}
@Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private Integer next = FixedIntRange.this.min;
@Override
public boolean hasNext() {
return next != null;
}
@Override
public Integer next() {
final Integer ret = next;
next = ret == max ? null : next + 1;
return ret;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
,然后遍历其通常:
for (final int i : new FixedIntRange(-10, 20)) {
// this will be run for each i in the range [-10, 20]
}
相关问题
- 1. 安全使用循环变量循环
- 2. 在使用变量循环
- 3. 使用变量 'for' 循环
- 4. 使用循环变量
- 5. 无法实现try/catch /最后变量是最终的
- 6. Python动态循环终止变量
- 7. 使用循环但始终执行最新循环 - node.js net-snmp
- 8. 声明本地变量为循环中的最终状态
- 9. 最终变量
- 10. 实现循环
- 11. Python:无法使用不同类型的变量终止循环
- 12. 什么是最终使用的循环变量中增强的for循环的目的是什么?
- 13. For循环最终输出
- 14. 使用循环FOR改变的变量
- 15. 初始化“最终”实例变量
- 16. Java最终变量
- 17. Java - 最终变量
- 18. Actionevent最终变量?
- 19. runOnUiThread中非最终变量的使用
- 20. 循环和变量变量
- 21. 变量变量(?) - PHP循环
- 22. 如何实现使用for循环?
- 23. 使用ArrayList实现循环队列
- 24. 最终实例变量在编译时已知值的使用
- 25. PHP循环实现
- 26. 最终与非最终正常变量
- 27. 在中环数字上使用最终的循环值
- 28. 实例变量在不修改循环
- 29. 我想使用循环中的变量,但while循环中定义的变量
- 30. 使用信号量在java中实现一个循环屏障
你的问题不清楚... – assylias 2013-03-21 18:37:17
哎呀,它可能是那么容易,因为'的(最终的AtomicInteger I =新的AtomicInteger(0); i.get()
yshavit
2013-03-21 19:15:04