2017-08-15 21 views
-5

嘿傢伙我得到這個錯誤我做了同樣的C和它的工作,但是當我在java中做它我得到錯誤「線程中的異常」主要「Java .lang.ArrayIndexOutOfBoundsException:5" 你可以看看這個 - >在java中的數組越界,但它在C工作

import java.util.Scanner; 

class sort { 

    public static void main(String args[]) { 

     Scanner obj = new Scanner(System.in); 
     int a[] = new int[5]; 
     int i, j; 
     int temp; 

     System.out.println("Enter the elements of array : "); 

     for (i = 0; i < 5; i++) { 
      a[i] = obj.nextInt(); 
     } 

     for (i = 0; i < 5; i++) 
      for (j = 0; j < 5; j++) { 
       if (a[i + 1] < a[i]) { 
        temp = a[i]; 
        a[i] = a[i + 1]; 
        a[i + 1] = temp; 
       } 
      } 

     for (i = 0; i < 5; i++) 
      System.out.println("\n" + a[i]); 

    } 
} 
+4

可能因爲C不檢查數組邊界? https://stackoverflow.com/questions/5554734/what-c​​auses-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it – jackarms

+0

在這段代碼中if(a [i + 1] < a [i])'if'i == 5' then OOB –

+0

我沒有理由懷疑跨語言的東西。 – ChiefTwoPencils

回答

0

這是錯誤在任何語言來訪問出界數組元素。

例如,在C:

int a[1]; 
int tmp = a[5]; 

是錯誤的(即使沒有崩潰或無execption)

所以你的java代碼是錯誤的,不以任何訪問任何出界元素語言。

1

你的問題是在這裏:

for (i = 0; i < 5; i++) 
     for (j = 0; j < 5; j++) { 
      // When `i` == `4` this accesses `a[5]` which does not exist. 
      if (a[i + 1] < a[i]) { 
-1

哥們,你可以不設置i等於或大於5(索引是0〜4) 所以當它達到我== 4在你的第二個循環你使用[i + 1]你會得到一個outOfBounException。

for (i = 0; i < 4; i++) 
      for (j = 0; j < 5; j++) { 
       if (a[i + 1] < a[i]) { 
        temp = a[i]; 
        a[i] = a[i + 1]; 
        a[i + 1] = temp; 
       } 
      }