For-each Loop in Java

后端 未结 3 844
误落风尘
误落风尘 2021-01-20 16:35

I have a sample code which creates an \"array\" of size 10 and tries to initialize it with reverse values in a For loop e.g:(9,8,7,6,5...0):

int[] array = ne         


        
相关标签:
3条回答
  • 2021-01-20 17:06

    This for loop, for (int k : array) is basically gives you the array value in detail this for loop is like -

    int k = array[0] = 9 int k = array[1] = 8 .....

    and again you are trying to print array[9] , array[8] which gives you result like 0,1,2... replace for( int k : array){ System.out.println(array[k]); }

    with for(int k : array){ System.out.println(k); }

    0 讨论(0)
  • 2021-01-20 17:08

    Basically, since (int k : array) causes k to go through the values in the array, not the indexes, what you've done is equivalent to

    System.out.println(array[array[0]]);
    System.out.println(array[array[1]]);
    System.out.println(array[array[2]]);
    System.out.println(array[array[3]]);
    ...
    System.out.println(array[array[9]]);
    

    which isn't what you want.

    0 讨论(0)
  • 2021-01-20 17:18

    You are already getting the values out of the array with your foreach loop, which you are using as an index again into the array, yielding the values in order again.

    Just print k. Change

    for (int k : array) {
        System.out.println(array[k]);
    }
    

    to

    for (int k : array) {
        System.out.println(k);
    }
    

    End of the output:

    9
    8
    7
    6
    5
    4
    3
    2
    1
    0
    
    0 讨论(0)
提交回复
热议问题