2014-10-08 82 views
-1

當我試圖將temp的值放入int[] unDupei位置時,問題似乎在我的for循環內。我得到的錯誤:爲什麼我會收到「ArrayIndexOutOfBoundsException:0」?

'Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at main.Main.main(Main.java:33)'

public static void main(String[] args) { 
    Scanner input = new Scanner(System.in); 
    int[] unDupe = {}; 
    System.out.print("Enter a number sequence (eg. '1 2 10 20'): "); 
    String dupe = input.nextLine(); 
    String[] dupeSplit = dupe.split(" "); 

    int temp; 
    for(int i = 0; i < dupeSplit.length; i++){ 
     temp = Integer.parseInt(dupeSplit[i]); 
     unDupe[i] = temp; // line 33 
    } 
} 
+0

int[] unDupe = new int[dupeSplit.length]; 

你沒有分配的數組的任何元素。 – OldProgrammer 2014-10-08 20:41:20

+0

Java數組的長度固定,創建後不能更改大小。如果你不知道你需要的最大長度,你可能需要爲「最糟糕的情況」分配數組,或者使用類似ArrayList的非固定長度的東西。 – 2014-10-08 20:45:51

回答

4

您正在使用int[] unDupe = {};聲明並初始化unDupe數組 - 但是,它沒有給出元素;一個零大小的數組。

只要你嘗試用任何東西索引它unDupe[i] = temp;你超出了數組的大小 - 你的索引超出範圍。對於一個數組,甚至有unDupe[0]該數組必須至少size = 1。

如果您未重複你的重複數據刪除陣列必須輸入,最多,同樣大小的輸入數組dupeSplit,所以你可以聲明int[] unDupe = new int[dupeSplit.length];你知道dupeSplit後的大小。稍後再聲明deDupe。

0

啓動unDupe你知道dupeSplit後的大小。

-1

使用

int[] unDupe = new int[100]; 

你可以用你的數組中需要但是很多東西取代百試。

+0

-1他確切知道他需要多少,即dupeSplit.length。 – MrHug 2014-10-08 20:45:19

2

當您將unDupe初始化爲{}時,您創建的長度爲0。因此,當您嘗試將元素放在索引0(或更高)的unDupe中時,會出現越界異常,因爲對於數組(在java中),只能將索引存儲在索引0...(length - 1)中。在獲得數字序列的大小後,通過初始化unDupe來解決這個問題。

public static void main(String[] args) { 
    Scanner input = new Scanner(System.in); 

    System.out.print("Enter a number sequence (eg. '1 2 10 20'): "); 
    String dupe = input.nextLine(); 
    String[] dupeSplit = dupe.split(" "); 
    int[] unDupe = new int[dupeSplit.length]; 

    int temp; 
    for(int i = 0; i < dupeSplit.length; i++){ 
     temp = Integer.parseInt(dupeSplit[i]); 
     unDupe[i] = temp; 
    } 
} 
1

由於您初始化unDupe爲空數組與={}符號不能寫入到它元素0(它沒有存儲器可用的話)。

而是試圖把的unDupe初始化拆分後,取而代之的是:

int[] unDupe = new int[dupeSplit.length]; 
0

這樣做:

String[] dupeSplit = dupe.split(" "); 
int[] unDupe = new int[dupeSplit.length]; 

現在unDupe的初始大小。

1
int[] unDupe = {}; 

是一個0元素的數組。嘗試訪問其中i = 0-> dupeSplit.length的unDupe [i]將導致拋出異常異常。如果沒有空間分配給自己,問自己如何訪問數組中的索引?即unDupe [0] - > ERROR,因爲unDupe的大小是0.沒有元素存在!

你可能想補充一點:這條線

String[] dupeSplit = dupe.split(" "); 
相關問題