[英]Why the following code gives an error
The code below gives me a compiling error. 下面的代码给了我一个编译错误。 It says I should have initialised v
somewhere before using it in the second loop while in the first loop everything seems fine. 它说我应该在第二个循环中使用它之前在某个地方初始化v
,而在第一个循环中一切似乎都很好。 I thought maybe it will implicitly initialised to 0. Appreciate any feedback on this. 我认为可能会将它隐式初始化为0。对此表示感谢。 Also, What is the best practice in such cases. 此外,在这种情况下的最佳做法是什么。
public static void main(String[] args) {
ArrayList<Integer> list=new ArrayList<Integer>();
ArrayList<Integer>[] list2=(ArrayList<Integer>[])new ArrayList[10];
for(int v:list)
System.out.println(v);
for(int v:list2[v])
System.out.println(v);
}
The scope of your first 'v' is limited to the first for loop. 您的第一个“ v”的范围仅限于第一个for循环。
So in the second loop, the 'v' you use in the subscript is not declared when it is first used. 因此,在第二个循环中,第一次使用下标时不会声明您在下标中使用的“ v”。
What do you expect to do in the second 'for'? 您希望在第二个“ for”中做什么? Print everything inside list2 ? 打印list2内的所有内容? If yes, then you need to make a nested for loop like this: 如果是,那么您需要制作一个嵌套的for循环,如下所示:
for(ArrayList<> innerList : list2)
for(int i : innerList)
System.out.println(i);
Notice that as list2 contains ArrayLists and not ints, then you cannot do the for as you had it in your code (the iterating variable cannot be an int). 请注意,由于list2包含ArrayLists而不是ints,因此您无法像在代码中那样进行for(迭代变量不能为int)。
您声明的第一个“ v”仅限于第一个for循环,而第二个“ v”仅限于第二个for循环,因此您可以在第二个for循环中使用第一个“ v”
Your code is similar to the following code. 您的代码类似于以下代码。
//begin loop 1
for(int v:list){
System.out.println(v);
}
//end loop 1
//begin loop 2
for(int v:list2[v]){
System.out.println(v);
}
//end loop 2
Here the variable v will lost to the program because it is limited to the first for loop. 在这里,变量v将丢失给程序,因为它仅限于第一个for循环。 (Same as method local variable) (与方法局部变量相同)
The correct code would be like this : 正确的代码如下:
for (int v : list) {
System.out.println(v);
for (int x : list2[v]) {
System.out.println(x);
}
}
Have look at this article http://www.java-made-easy.com/variable-scope.html . 看一下本文http://www.java-made-easy.com/variable-scope.html 。
It states. 它指出。
Any variables created inside of a loop are LOCAL TO THE LOOP. 在循环内部创建的任何变量都是局部的。 This means that once you exit the loop, the variable can no longer be accessed! 这意味着一旦退出循环,就无法再访问该变量! This includes any variables created in the loop signature. 这包括在循环签名中创建的所有变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.