2014-02-25 96 views
0

試圖清理代碼,最初我用寫入陣列,這是可笑長的這種方法時,我必須重複20次寫入陣列

 if (ant.getAntNumber() == 3) 
     { 
      numbers3.add(ant.getCol()); 
      numbers3y.add(ant.getRow()); 
     } 

     if (ant.getAntNumber() == 4) 
     { 
      numbers4.add(ant.getCol()); 
      numbers4y.add(ant.getRow()); 
     } 

我試圖使用for循環做,但我無法弄清楚如何添加使用字符串值數組,因爲它認爲它是一個字符串,而不是試圖用數組

for (int j = 0; j<maxAnts; j++) 
     { 
      String str = "numbers" + j; 
      String str2 = "numbers" + j + "y"; 
      //this part doesnt work 
      str.add(ant.getCol()); 

     } 

任何建議將是有益的

+0

你的'number3','number4',...,'numberN'應該屬於一個數組,這就是它。 – moonwave99

+0

將字符串數組聲明爲String [] str = new String()[SIZE]; – ItachiUchiha

+0

說abt數組或集合? – Kick

回答

1

在Java中,你不能使用String對象的值引用實際變量名稱。 Java會認爲你試圖在String對象上調用add對象,該對象不存在,並且給你編譯錯誤。

爲避免重複,您需要將List添加到您可以索引的兩個主列表中。

在你的問題中,你提到了數組,但你打電話add,所以我假設你真的指的是某種List

List<List<Integer>> numbers = new ArrayList<List<Integer>>(20); 
List<List<Integer>> numbersy = new ArrayList<List<Integer>>(20); 
// Add 20 ArrayList<Integer>s to each of the above lists in a loop here. 

然後你就可以越界檢查ant.getAntNumber(),並用它作爲索引到你的主人名單。

int antNumber = ant.getAntNumber(); 
// Make sure it's within range here. 

numbers.get(antNumber).add(ant.getCol()); 
numbersy.get(antNumber).add(ant.getRow()); 
+0

然後我會如何獲取這些數據?目前正在使用此從舊版本 對(INT I = 0; I Mivox

+0

像填充列表,調用'上GET'您主列表來獲取每個螞蟻的適當列表,然後遍歷這兩個列表來重新獲得你的'x'和'y'值。 – rgettman

+0

你提供的解決方案是給我一個索引越界異常,因爲它說它的大小始終爲0,這是因爲我試圖在它存儲在它之前的東西之前得到它嗎? – Mivox

1

這個怎麼樣?

Ant[] aAnt = new Ant[20]; 

//Fill the ant-array 

int[] aColumns = new int[aAnt.length]; 
int[] aRows = new int[aAnt.length]; 

for(int i = 0; i < aAnt.length; i++) { 
    aColumns[i] = aAnt[i].getCol(); 
    aRows[i] = aAnt[i].getRow(); 
} 

或列表:

List<Integer> columnList = new List<Integer>(aAnt.length); 
List<Integer> rowList = new List<Integer>(aAnt.length); 

for(Ant ant : aAnt) { 
    columnList.add(ant.getCol()); 
    rowList.add(ant.getRow()); 
} 

或用COL /行對象:

class Coordinate { 
    public final int yCol; 
    public final int xRow; 
    public Coordinate(int y_col, int x_row) { 
     yCol = y_col; 
     xRow = x_row; 
    } 
} 

//use it with 

List<Coordinate> coordinateList = new List<Coordinate>(aAnt.length); 
for(Ant ant : aAnt) { 
    coordinateList.add(ant.getCol(), ant.getRow()); 
} 
1

你的代碼的一個直接的端口將使用兩個Map<Integer, Integer>其存儲X和Y座標。從你的代碼看來,螞蟻數似乎是唯一的,也就是說,我們只需要存儲每個螞蟻數的單個X和Y值。如果您需要爲每個螞蟻號存儲多個值,請使用List<Integer>作爲Map的值類型。

Map<Integer, Integer> numbersX = new HashMap<Integer, Integer>(); 
Map<Integer, Integer> numbersY = new HashMap<Integer, Integer>(); 

for(Ant ant : ants) { 
    int number = ant.getAntNumber();   
    numbersX.put(number, ant.getCol()); 
    numbersY.put(number, ant.getRow()); 
}