2012-10-01 131 views
0

我遇到了組合數組值的問題。我想結合數組的兩個值來爲另一個數組創建一個值。這是我的代碼:連接數組的兩個元素以創建新的數組元素

String [] candid = {"A","B","C","D","E"}; 

String [] candidates = new String[candid.length]; 
     for (int i=0;i<candid.length;i++){ 
      candidates[i] = candid[i]+","+candid[i+1]; 
     } 

但是命令candidates[i] = candid[i]+","+candid[i+1];不起作用。

+3

該行連接兩個「字符串」。如果您顯示輸入和輸出樣本,這將非常方便。 –

+2

什麼是候選人? –

+2

「不工作」是什麼意思?您可以點擊帖子左下方的「修改」以隨時更新。 –

回答

2

你可能想聲明candidates作爲

String [] candidates = new String[candid.length-1]; 

詩注:假設candidatecandid

更新:

按OP的評論candidates被初始化爲

String [] candidates = new String[candid.length]//Length of candid is used in the 
question 

所以初始分析成立,代碼將生成ArrayIndexOutOfBoundsException最後一個元素,即i+1

發生這種情況的原因是陣列中只有6個元素,並且當您嘗試訪問7 th元素時i is 6 the element。數組索引是我正在裁判的地方的-1。所以,如果長度爲5您試圖訪問6

+1

我們不一定*知道這是真的。 '候選人'可能總是長度爲4 ... –

+0

有'String []坦率'所以循環可以*正確*(當且僅當'candid.length

+0

Err。更正了答案。 –

1

不知道你想candidate.length靜置,但是這是我嘗試,它似乎工作:

public static void main(String[] args) { 
    String[] candid = { "A", "B", "C", "D", "E" }; 
    String[] candidates = new String[candid.length-1]; 
    for (int i = 0; i < candid.length-1; i++) { 
     candidates[i] = candid[i] + "," + candid[i + 1]; 
    } 
    for (String s : candidates) { 
     System.out.println(s); 
    } 
} 

替換「候選人。長度」與 「candid.length-1」

輸出結果:

A,B
B,C
C,d
D,E

+0

我忘了用坦誠替換候選人。但是,你的代碼是可行的。謝謝你的幫助。 – diyana