gpt4 book ai didi

java - For 循环卡在数组移位器中的同一点

转载 作者:行者123 更新时间:2023-12-01 09:07:41 25 4
gpt4 key购买 nike

该方法应该采用一个整数数组、一个整数值和一个整数索引。该方法应在给定索引处插入值,并将后面的值移动 1。

例如这个insertValue(a, 100, 2) 会将数组 {1, 2, 3, 4, 5} 更改为 {1, 2, 100, 3, 4}

这是我用来执行该方法的代码:

public static void main(String[] args) {
int[] and = {4,2,6,1,4,3,4};
insertValue(and, 100, 2);
}

这是方法本身:

public static void insertValue(int[] a,int b , int c) {
for(int i = c; i < a.length-1; i++) {
a[i+1] = a[i];
System.out.print(a[i]);
}
a[c] = b;
System.out.print(a[c]);
}

这是我得到的输出:

6666100

所以它不仅被一个一个的数字卡住了,而且还停在了错误的位置。这是一项家庭作业,因此对我出错的地方进行解释会很有帮助。

最佳答案

由于数组长度为 7,b 为 2,n 为 100,因此您的方法执行以下操作:

      // array originally contains {4,2,6,1,4,3,4}
a[3] = a[2];
// array now contains {4,2,6,6,4,3,4}
System.out.print(a[2]); // prints 6
a[4] = a[3];
// array now contains {4,2,6,6,6,3,4}
System.out.print(a[3]); // prints 6
a[5] = a[4];
// array now contains {4,2,6,6,6,6,4}
System.out.print(a[4]); // prints 6
a[6] = a[5];
// array now contains {4,2,6,6,6,6,6}
System.out.print(a[5]); // prints 6
a[2] = 100;
// array now contains {4,2,100,6,6,6,6}
System.out.print(a[100]); // prints 100

这就是您获得输出 6666100 的原因。

关于java - For 循环卡在数组移位器中的同一点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41134001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com