简体   繁体   中英

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. I thought maybe it will implicitly initialised to 0. Appreciate any feedback on this. 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.

So in the second loop, the 'v' you use in the subscript is not declared when it is first used.

What do you expect to do in the second 'for'? Print everything inside list2 ? If yes, then you need to make a nested for loop like this:

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).

您声明的第一个“ 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. (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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM