2017-08-10 108 views
-1

沒有人知道如何使用數組作爲參考通過使用循環來獲得另一個數組中的元素或另一個有用的方法 例如,我得到多個陣列的下方,並且我運行該程序之後的輸出陣列將具有Java數組,使用數組的元素作爲參考,以獲得從另一個數組元素,然後創建另一個新的數組

int[] array = { 0, 1, 3, 4, 5, 6, 8 }; 
int[] c = { 18, 19, 20, 21, 22, 23, 24, 25, 26 }; 

我運行程序之後

output ={18,19,21,22,23,24,26} 


//this is generate through below 
output[0]=c[0]; 
output[1]=c[1]; 
output[2]=c[3]; 
output[3]=c[4]; 
+3

究竟什麼是你的問題?你想知道你是否可以用循環實現輸出而不是硬編碼索引? –

+1

可以這樣'C [數組[0]]'訪問值。添加一個for循環來遍歷'array',然後你就可以開始了。 – Kayaman

+0

是的,只是不知道是否有任何其他更好的方式來實現這一目標 –

回答

1

由於數組索引是通常的整數值,它們不要噸需要被硬編碼:

int[] indeces = { 0, 1, 3, 4, 5, 6, 8 }; 
int[] values = { 18, 19, 20, 21, 22, 23, 24, 25, 26 }; 
int[] output = new int[indeces.length] 

for (int i = 0; i<indeces.length; i++) { 
    output[i] = values[indeces[i]]; 
} 

(代碼未測試)

0

您可以訪問值這樣的:

output[i]=c[array[i]]; 

我把它留給你周圍聚集聲明:)

0

環路您可以使用下面的代碼來實現這一

int[] array = { 0, 1, 3, 4, 5, 6, 8 }; 
int[] c = { 18, 19, 20, 21, 22, 23, 24, 25, 26 }; 
int output [] = new int[array.length]; 
int cnt =0 ; 
for(int a : array){ 
    if(a < c.length && a >= 0){ 
     output[cnt++]=c[a]; 
     } 
} 

這是一個非常簡單的解決辦法當然還有其他的方法來達到同樣的

相關問題