Hue*_*Tan 0 java foreach for-loop
也许这是一个愚蠢的问题,但我仍然想知道
如果我使用
ArrayList<Integer> Data=new ArrayList<Integer>();
for(int data:Data)
//some code here
//print out the iteration times
Run Code Online (Sandbox Code Playgroud)
我想打印出迭代次数(而不是执行时间)
而不使用
for int i;i<blahblahblah;i++) output i
Run Code Online (Sandbox Code Playgroud)
例如输出
output:
This is iteration times: 1 the data is : blahblahblah
This is iteration times: 2 the data is : blahblahblah
This is iteration times: 3 the data is : blahblahblah
Run Code Online (Sandbox Code Playgroud)
一种方法是:在循环外定义一个计数器变量并递增计数器.
ArrayList<Integer> Data = new ArrayList<Integer>();
int iterCnt = 0;
for (int data : Data) {
iterCnt++;
System.out.println(iterCnt);
}
Run Code Online (Sandbox Code Playgroud)