gpt4 book ai didi

java - 打印时遇到问题 (java)

转载 作者:行者123 更新时间:2023-12-01 06:08:23 24 4
gpt4 key购买 nike

我在更改后打印数组时遇到问题。该代码应该包含一个数组,然后我插入一个应该成为索引号的数字(本例为 4)。然后将该数字移至数组的末尾,而所有其他数字则在数组中向上移动一个索引以填充空白位置。由于某种原因,它不允许我在进行更改后打印数组。

public static int SendaAftast(int a[], int i) {
for(int k = 0; k <a.length; k++) {
int temp = a[k];

while(k <a.length) {
a[k] = a[k] - 1;
}
a[a.length] = temp;
}
return a[i];
}

public static void main(String[] args) {
int[] a = new int [20];
for(int i = 0; i < a.length; i++) {
a[i] = (int)(Math.random()*a.length)+1;
}

System.out.println(SendaAftast(a, 4));

最佳答案

1。无限循环

您没有打印任何内容,因为您的代码中有一个无限循环,即:

while(k < a.length) {
a[k] = a[k] - 1;
}

如果条件k < a.lengthtrue它将永远是true因为你永远不会在循环内改变它的状态,换句话说 k在此循环中从未被修改,它仅在外部修改并且 a.length也永远不会改变。

2。 ArrayIndexOutOfBoundsException

代码中的第二个问题是 a[a.length] = temp;这将抛出 ArrayIndexOutOfBoundsException如果由于数组的索引来自0而到达至a.length - 1 .

3。新代码SendaAftast

而且你的方法SendaAftast似乎写得不正确,据我了解您的上下文,它应该是这样的:

public static int SendaAftast(int a[], int i) {
int temp = a[i];
// Move everything from i to a.length - 2
for(int k = i; k < a.length - 1; k++) {
a[k] = a[k + 1];
}
// Set the new value of the last element of the array
a[a.length - 1] = temp;
return a[i];
}

或者使用 System.arraycopy(src, srcPos, dest, destPos, length) 甚至更快:

public static int SendaAftast(int a[], int i) {
int temp = a[i];
// Move everything from i to a.length - 2
System.arraycopy(a, i + 1, a, i, a.length - 1 - i);
// Set the new value of the last element of the array
a[a.length - 1] = temp;
return a[i];
}

4。如何打印数组?

要打印数组,必须首先将其转换为 String最简单的方法是使用 Arrays.toString(myArray)所以你可以像这样打印它:

System.out.println(Arrays.toString(a));

关于java - 打印时遇到问题 (java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40038614/

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