参考迭代次数在Java的的foreach [英] Reference to the iteration number in Java's foreach

查看:1136
本文介绍了参考迭代次数在Java的的foreach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何可以参考在foreach数组的索引?

我的code

 的String [] NAME = {你好,世界};
对于(INT K:名称[K]){
   ---切---
}

我期待那在foreach -loop会

  1。在第一次迭代设置k = 0,这样的名字[0]正常工作
2.设置k = 1在下一迭代...

我得到错误信息


  

的foreach并不适用于前pression型



解决方案

这是因为指数使用的foreach 语法时不可用。你必须使用的传统的的循环,如果你需要的指数:

 的for(int i = 0; I< names.length;我++){
   字符串名称=名称[I]
}

如果您的不需要的指标,标准的foreach 就足够了:

 为(字符串名称:名称){
    // ...
}

修改很明显,你可以用一个计数器的景气指数,但你必须用循环的范围以外的变量,我认为是不可取

How can you refer to the index of an array in the foreach?

My code

String[] name = { "hello", "world" };
for ( int k : name[k] ) {
   --- cut ---
}

I expecting that the foreach -loop will

1. set k = 0 in first iteration so that name[0] works correctly
2. set k = 1 in the next iteration...

I get the error message

foreach not applicable to expression type

解决方案

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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