Arrays and enhanced for loops?

后端 未结 6 494
闹比i
闹比i 2021-01-22 15:19

Can someone please explain what is going on in this method?

class test{  
public static void main(String args[])
{
   int[] x = new int[4]; 
   int[] xy = new i         


        
6条回答
  •  走了就别回头了
    2021-01-22 15:27

    In your case you need only for-loop and not enhanced for-loop:

    for(int j = 0 ; x.length > j; j ++) { 
       xy[j] += 1;
    }
    

    Problem with your code is that your loop traverse only at index 0 of xy hence you get xy as [4, 0, 0, 0]

    int[] x = new int[4];//default values [0, 0, 0, 0]
    int[] xy = new int[4]; //default values [0, 0, 0, 0]
    for(int j : x) { // j is always 0
       xy[j] += 1;// xy[0] += 1
    }
    

提交回复
热议问题