2014-02-25 52 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()); 
}