打印有问题(java)

打印有问题(java),java,arrays,numbers,Java,Arrays,Numbers,更改后打印阵列时出现问题。代码应该包含一个数组,然后我插入一个数字,这个数字应该成为本例4的索引号。然后取该数字并移动到数组的后面,而所有其他数字在数组中向上移动一个索引以填充空白点。由于某些原因,它不允许我在进行更改后打印数组 public static int SendaAftast(int a[], int i) { for(int k = 0; k <a.length; k++) { int temp = a[k]; while(k <

更改后打印阵列时出现问题。代码应该包含一个数组,然后我插入一个数字,这个数字应该成为本例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));
更改行:

a[k] = a[k] - 1;

再见

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

while(k < a.length) {
    a[k] = a[k] - 1;
}
甚至更快地使用:

4.如何打印数组? 要打印数组,必须首先将其转换为字符串,最简单的方法是使用Arrays.toStringmyArray,以便按如下方式打印:

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.out.println(Arrays.toString(a));

您的SendaAftast应该如下所示。内部while循环是无用的,这也是您的程序无法打印的无限循环的原因。此外,变量“a”不能按其自身大小编制索引,因为数组中的计数从0-a.length-1开始,因此要获取数组的最后一个值,您应该使用[a.length-1]而不是[a.length]。

那么,您的问题是什么?无限循环?ArrayIndexOutOfBoundsException?抱歉,它根本不打印任何内容,尽管我希望它在我进行更改后打印数组注意:a[a.length]。数组的第一个可用索引是0,最后一个是arrayLength-1。[a.length]超出范围,最后可用的索引是[a.length-1]。为什么这会修复无限循环或ArrayIndexOutOfBoundsException?您应该努力解释为什么您的解决方案会修复OP的问题,这通常意味着您也应该解释实际问题。您是对的。这是第一条评论,下次我会做得更好!
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];
}
System.out.println(Arrays.toString(a));
public static int SendaAftast(int a[], int i) {
    int temp = a[i];
    for (int k = i; k < a.length-1; k++) {
        a[k] = a[k+1] ;
    }
    a[a.length - 1] = temp;
    return a[i];
}