2012-12-12 32 views
0

我想將字符串數組中的值存儲到另一個字符串數組中。但是,我得到下面的代碼的「NullPointerException」錯誤。 「imagesSelected」是一個字符串數組,裏面存儲着值。但是當我想在substring之後將它移動到另一個字符串數組時,我得到錯誤。我相信是因爲最後一行代碼。我不知道如何使它工作。將值存儲到字符串數組中

String[] imageLocation; 

     if(imagesSelected.length >0){ 
     for(int i=0;i<imagesSelected.length;i++){ 
      int start = imagesSelected[i].indexOf("WB/"); 
      imageLocation[i] = imagesSelected[i].substring(start + 3); 
     } 
     } 
+0

您需要初始化'imageLocation'陣列到合適的大小。 – gsingh2011

+0

add print stack trace –

+1

你沒有初始化數組的字符串''String [] imageLocation = new String [x];''是嗎? – 2012-12-12 04:34:15

回答

5

你需要做這樣的事情:

String[] imageLocation = new String[imagesSelected.length]; 

否則imageLocationnull

順便說一句,你不需要圍繞你的循環if。這是完全多餘的,因爲這將是在循環開始時使用的相同邏輯。

+0

謝謝你的回答。這解決了我的問題。 –

2

您必須爲imageLocation分配內存。

imageLocation = new String[LENGTH]; 
+0

我已經解決了我的問題。但是,仍然感謝你的回答和你的時間! –

1

你的最終解決方案的代碼應該像如下,或編譯器會給你imageLocation可能尚未初始化

String[] imageLocation = new String[imagesSelected != null ? imagesSelected.length : 0]; 

    if (imagesSelected.length > 0) { 
     for (int i = 0; i < imagesSelected.length; i++) { 
      int start = imagesSelected[i].indexOf("WB/"); 
      imageLocation[i] = imagesSelected[i].substring(start + 3); 
     } 
    } 
+0

謝謝你的回答! –

+0

@IssacZH。歡迎你好友 –

1

看看這個代碼

String[] imageLocation; 

     if(imagesSelected.length >0){ 
      imageLocation = new String[imageSelected.length]; 
     for(int i=0;i<imagesSelected.length;i++){ 
      int start = imagesSelected[i].indexOf("WB/"); 
      imageLocation[i] = imagesSelected[i].substring(start + 3); 
     } 
     } 
+0

我已經開始工作了。感謝您的回答和您的時間! –

+0

:)我最歡迎 –

4

imageLocation [I]錯誤

你初始化了imageLocation嗎?

我相信這個錯誤是因爲你試圖指向字符串數組中不存在的位置。 imageLocation [0,1,2,3 ... etc]還不存在,因爲字符串數組尚未初始化。

嘗試的String [] imageLocation [但是長期要在陣列刊]

+0

謝謝你的答案!它已經在工作了。 –

相關問題