本文介绍了参考迭代次数在Java的的foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何可以参考在foreach数组的索引?
我的code
的String [] NAME = {你好,世界};
对于(INT K:名称[K]){
---切---
}
我期待那在foreach -loop会
1。在第一次迭代设置k = 0,这样的名字[0]正常工作
2.设置k = 1在下一迭代...
我得到错误信息
解决方案
That's because the index is not available when using the foreach
syntax. You have to use traditional iteration if you need the index:
for (int i =0; i < names.length; i++) {
String name = names[i];
}
If you do not need the index, the standard foreach
will suffice:
for (String name : names) {
//...
}
EDIT: obviously you can get the index using a counter, but then you have a variable available outside the scope of the loop, which I think is undesirable
这篇关于参考迭代次数在Java的的foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!