Why is the output of this code 111111?

后端 未结 9 1957
星月不相逢
星月不相逢 2021-01-13 20:10

This is the code. I tried to solve it, but I can\'t understand how its output is 111111?

public class Test { 
      public static void main(String[] args) {
         


        
9条回答
  •  爱一瞬间的悲伤
    2021-01-13 20:51

    Hi I will try to explain what is happening in this code snippet

    public class Test { 
      public static void main(String[] args) {
        int list[] = {1, 2, 3, 4, 5, 6};
    

    This line is the equivalent of the following code

        int list[] = new int[6];
        list[0] = 1;
        list[1] = 2;
        list[2] = 3;
        list[3] = 4;
        list[4] = 5;
        list[5] = 6;
    
    
        for (int i = 1; i < list.length; i++)
          list[i] = list[i - 1];
    

    this loop is the equivalent of the following code

        list[1] = list[0];
        list[2] = list[1];
        list[3] = list[2];
        list[4] = list[3];
        list[5] = list[4];
    

    which because list[0] = 1 is the equivalent of the following

        list[1] = 1;
        list[2] = 1;
        list[3] = 1;
        list[4] = 1;
        list[5] = 1;
    
    
        for (int i = 0; i < list.length; i++)
          System.out.print(list[i] + " ");
      }
    }
    

    Which is why you are getting the output you are getting

提交回复
热议问题