簡體   English   中英

如何修復數組索引超出范圍的錯誤?

[英]How to fix array index out of bounds error?

我得到的錯誤

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 610
at Fib.sorted(Fib.java:67)
at Fib.main(Fib.java:17)

我的密碼

public class Fib
{
    public static void main(String args[]) 
    {
        System.out.println(Arrays.toString( fiblist) );
        System.out.println(Fib.add());
        System.out.println(Fib.square());
        System.out.println(Fib.reversal());
        System.out.println(Fib.sorted());
    }

     public static int fiblist[] = {1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765};
     public static int fiblen = fiblist.length;

     public Fib() 
     {
        // Do nothing
     }

     public static ArrayList<Integer> sorted()
     {
         ArrayList sorted = new ArrayList();

         for(int counter = 0; counter < fiblist[4]; counter++ )
         {
             int temp1 = fiblist[counter];
             System.out.println("Elements stored " + temp1);
         }
         for(int counter = fiblist[14]; counter < fiblist[19]; counter++)
         {
             int temp2 = fiblist[counter];
             System.out.println("Last Elements stored " + temp2);
         }
         return sorted;
    }
}

我試圖將數組的最后5個元素存儲在temp 2中。然后將其切換。 有沒有更簡單的方法可以做到這一點? 切換數組的前五個元素與后五個元素? 您將如何通過for循環切換它們?

您在混淆數組索引和值。 fiblist [19]是6765。您希望計數器從0變為4,從14變為19,而不是fiblist [19]。

for(int counter = 0; counter < 4; counter++ )
{
    int temp1 = fiblist[counter];
    System.out.println("Elements stored " + temp1);
}

for(int counter = 14; counter < 19; counter++)
{
    int temp2 = fiblist[counter];
    System.out.println("Last Elements stored " + temp2);
}

這有效

for(int i=0;i<fiblist.length;i++){
   System.out.print(fiblist[i]+",");
}
System.out.println();

for (int i=0;i<5;i++){
    temp=fiblist[i];
    fiblist[i]=fiblist[fiblist.length-i-1];
    //the first ellement= the last
    //the second=second from last...
    fiblist[fiblist.length-1-i]=temp;
}

for(int i=0;i<fiblist.length;i++){
    System.out.print(fiblist[i]+",");
}

輸出:

1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,
6765,4181,2584,1597,987,8,13,21,34,55,89,144,233,377,610,5,3,2,1,1,

嘗試這個。 這是一種排序算法(雖然相當差)

public static void sort(int[] a) {
    int iMin;
    int n = a.length;
    for (int j = 0; j < n-1; j++) {
        iMin = j;
        for (int i = j+1; i < n; i++) {
            if (a[i] < a[iMin]) {
                iMin = i;
            }
        }
        if(iMin != j) {
            swap(j, iMin, a);
        }
    }
}

public static void swap(int i, int j, int[] arr){
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

暫無
暫無

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

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