2015-01-14 19 views
-1

幾乎完成了使強力球遊戲,但是這是一個語義錯誤。嘗試比較兩個5個整數的數組並返回匹配數。但是,如果有重複的號碼,則該號碼匹配多次。我需要在匹配後刪除兩個數字。爲java強力球遊戲刪除int數組中的索引

我嘗試使用ArrayList的就在這裏的建議,但ArrayList的是「未使用的import語句」,並卸下襬臂是「無法解析法」

import java.util.ArrayList; 

for (int i = 0; i < 5; i++) { 
    for (int j = 0; j < 5; j++) { 
       if (balls[i] == yballs[j]) { 
        match++; 
        balls.remove(); 
        remove(yballs, yballs[j]); 
       } 
      } 
     } 

public static int[] remove(int[] symbols, int c) { 
    for (int i = 0; i < symbols.length; i++) { 
     if (symbols[i] == c) { 
      int[] copy = new int[symbols.length-1]; 
      System.arraycopy(symbols, 0, copy, 0, i); 
      System.arraycopy(symbols, i+1, copy, i, symbols.length-i-1); 
      return copy; 
     } 
    } 
    return symbols; 
} 
+0

沒有任何方法刪除數組中。你還沒有創建任何ArrayList這就是爲什麼沒有使用的導入。所以我不認爲這是問題,你的邏輯缺少別的東西 – Prashant

+0

你不能從數組中刪除東西。創建一個新的ans數組或使用'ArrayList'。我的意思是真正使用它,而不是僅僅導入該類。 – Tom

+0

使用'ArrayList',你可以創建一個新的'ArrayList'來跟蹤你找到的所有重複項,然後在列表 – Ascalonian

回答

0

作爲一個解決方案中使用ArrayList

你可以填充2 ArrayLists來表示球的兩個集合和一個容納比賽的球:

List<Integer> balls = new ArrayList<Integer>(); 
List<Integer> yballs = new ArrayList<Integer>(); 
List<Integer> matches = new ArrayList<Integer>(); 

balls.add(<ball number>); 
... 
yballs.add(<ball number>); 
... 

然後,您將通過每個ArrayList爲:

for (Integer ballNumber : balls) { 
    for (Integer yballNumber : yballs) { 
     if (ballNumber == yballNumber) { 
      matches.add(ballNumber); 
     } 
    } 
} 

,並從兩個List動手清除所有重複:

balls.removeAll(matches); 
yballs.removeAll(matches); 

如果你不想將它們全部刪除,只是刪除重複的一個,你可以這樣做:

for (Integer match : matches) { 
    balls.remove(match); 
    yballs.remove(match); 
} 
+0

當我嘗試這樣做時,鑽石會給出錯誤「在此語言級別不支持鑽石類型」任何想法是什麼? –

+0

你使用的是什麼版本的Java? – Ascalonian

+0

我還更新了代碼,把'整數'放入鑽石 – Ascalonian