簡體   English   中英

為什么它一直在我的代碼上說“ArrayIndexOutOfBoundsException”?

[英]Why does it keep saying “ArrayIndexOutOfBoundsException” on my code?

所以我是編碼的新手,我正在使用Drjava。
我剛從我的類中得到一個賦值,要求用戶將整數輸入到兩個數組中(用戶必須在每個數組中輸入從最小到最大的整數)。
然后我必須組合兩個數組並從最小到最大排序新數組。
我想我想出了如何做到這一點並且它編譯得很好,但它一直說在我運行代碼並輸入一些數字后出現了OutOfBoundsException。

為什么一直這樣做,我該如何解決?

謝謝。

class Main{

     public static void main (String str[]) throws IOException {
          Scanner scan = new Scanner (System.in);

          System.out.println("Enter the values for the first array, up to 10000 values, enter a negative number to quit");

          int[] array1= new int[10000];
          int x=0;
          int x1=0;
          int v=1;
          for(int where=1; x>=0; where++) {
            x= scan.nextInt();
            array1[where]=x; 
            x1++;
            if((array1[where]<array1[where-1])&&(x>=0)){
              System.out.println("ERROR: Array not in correct order");
              x=-326;}
          }

          System.out.println("Enter the values for the second array, up to 10000 values, enter a negative number to quit");

          int[] array2= new int[10000];
          int y=0;
          int y1=0;
          int w=1;
          for(int wher=1; y>=0; wher++) {
            y= scan.nextInt();
            array2[wher]=y; 
            y1++;
            if((array2[wher]<array2[wher-1])&&(y>=0)){
              System.out.println("ERROR: Array not in correct order");
              y=-326;}
          }

          if(x!=-326) {
          System.out.println("First Array: ");
          int where=x1;
          for(v=1; v<(where); v++) {
            System.out.println(array1[v]); }}

          if(y!=-326) {
          System.out.println("Second Array: ");
          int wher=y1;
          for(w=1; w<(wher); w++) {
            System.out.println(array2[w]); }} 

          int[] array3= new int[v+w];
          int a=0;
          int b=0;
          while((a+b)<(v+w-3)) {
            while(array1[v-a]>array2[w-b]) {
              array3[w+v-a-b]=array1[v-a];
              a++;}
            while(array2[w-b]>=array1[v-a]) {
              array3[v+w-a-b]=array2[w-b];
               b++;}
          }

          if((y!=-326) && (x!=-326)) {
          System.out.println("Merged Array: ");
          int c=0;
          while((v+w-c)>=2){
            System.out.println(array3[v+w-c]);
            c++;                  }
          } 

     }

}

在你的第一個for循環中,當where = 10000 ,它會嘗試訪問不存在的array1[10000] 所以你試圖訪問一個“超出界限”的索引。

您需要確保不要嘗試訪問不存在的索引。

由於您定義了array1 = new int[10000] ,這意味着您只能訪問索引0 - 9999.任何超過array1[9999]都會拋出相同的錯誤“ArrayIndexOutOfBounds”。 我認為這是一個非常明確的錯誤信息。

暫無
暫無

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

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