簡體   English   中英

打印時遇到問題(java)

[英]Having trouble printing (java)

更改后我無法打印陣列。 該代碼應該包含一個數組,然后插入一個應該成為索引號的數字(本例為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; 如果由於數組的索引從0a.length - 1到達,它將拋出ArrayIndexOutOfBoundsException

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));
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];
}

您的SendaAftast應該看起來像這樣。 內部的while循環無用,這也是導致無限循環導致程序無法打印的原因。 同樣,變量“ a”不能按其自身大小進行索引,因為數組中的計數從0開始-a.length-1,因此要獲取數組的最后一個值,應使用a [a.length-1]而不是a [長度]。

更改行:

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

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

再見!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM