Why is the output of this code 111111?

后端 未结 9 1886
星月不相逢
星月不相逢 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:41

    It's all because of this loop,

    for (int i = 1; i < list.length; i++)
    list[i] = list[i - 1];
    

    What happened is, your first value is 1, As per the loop It assigns that value to the corresponding second element of the list Array.

    That means if your list is supposed to have 10 as first element of array like this

    int list[] = {10, 2, 3, 4, 5, 6};
    

    It will print 10,10,10,10,10,10

提交回复
热议问题