2016-08-12 138 views
4

我一直在一個小小的Java項目中工作,但我無法弄清楚如何根據另一個數組上的值覆蓋數組的元素。根據另一個數組的值重寫一個Java數組

基本上我有兩個數組:repeated[] = {1,4,0,0,0,3,0,0}hand[] = {1,2,2,2,2,6,6,6}我用repeated[]計數的時間出現在hand[]若干量,並且如果它是3和7之間,應以零,但我覆蓋相應的元素在hand[]當它應該給我{1,0,0,0,0,0,0,0}時,繼續得到這個輸出{1,0,0,2,2,6,0,6}。我究竟做錯了什麼?

public static void main(String[] args) { 
    int repeated[] = {1,4,0,0,0,3,0,0}; 
    int hand[] = {1,2,2,2,2,6,6,6}; 
    for(int z=0;z<repeated.length;z++){ 
     if(repeated[z]>=3 && repeated[z]<8){ 
      for(int f:hand){ 
       if(hand[f]==(z+1)){ 
        hand[f]=0; 
       } } } } 
    for(int e:hand){ 
     System.out.print(e+","); 
    } 
    } 
+1

重複[I]包含的那i + 1的發生在手的次數;這是用意嗎? –

回答

3

首先,repeated中的值偏移1(因爲Java數組從零開始索引)。接下來,您需要測試該值是否爲>= 3(因爲6只出現3次)。而且,您可以使用Arrays.toString(int[])來打印陣列。像,

public static void main(String[] args) { 
    int repeated[] = { 1, 4, 0, 0, 0, 3, 0, 0 }; 
    int hand[] = { 1, 2, 2, 2, 2, 6, 6, 6 }; 
    for (int z = 0; z < repeated.length; z++) { 
     if (repeated[hand[z] - 1] >= 3) { 
      hand[z] = 0; 
     } 
    } 
    System.out.println(Arrays.toString(hand)); 
} 

輸出是

[1, 0, 0, 0, 0, 0, 0, 0] 
+0

謝謝你! :) – agapito

相關問題