ArrayList объектов, которые в конечном итоге равняются последнему объекту - PullRequest
0 голосов
/ 29 ноября 2018

У меня проблема, которую я пытался решить в течение нескольких дней.Эта проблема заключается в том, что когда я в конце создаю ArrayList объектов, все они равны последнему объекту.Я считаю, что это как-то связано с постоянным добавлением одного и того же объекта, но из того, что я могу сказать, я создаю новый каждый раз.

Смысл этой программы должен состоять в создании множества разных ячеекили в целях симуляции (люди), которые впоследствии могут взаимодействовать друг с другом в зависимости от их случайных атрибутов.

Это код, с которым у меня возникают проблемы *

private ArrayList<Cell> cellsList = new ArrayList<Cell>(); //This appears before the Class is created
private int startingCellNumber = 10; //This appears before the Class is created

//This is inside the class
//Go through and create the starting cells
for(int index=0; index < startingCellNumber; index++) {
  cellsList.add(new Cell());
}

Любая помощь будет принята с благодарностьюЯ знаю, что есть вопросы, похожие на этот вопрос о переполнении стека, но все ответы на них не решили мою проблему.

Оба полных кода (написано в Java Processing) The Runner

private ArrayList<Cell> cellsList = new ArrayList<Cell>();
private int startingCellNumber = 10;

void setup() {
  //Set up the background stuff
  size(600,400);
  frameRate(30);
  noStroke();


  //Go through and create the starting cells
  for(int index=0; index < startingCellNumber; index++) {
    //Cell newCell = new Cell();
    cellsList.add(new Cell());
    System.out.println(index + " : " + cellsList.get(index).getColonyColor() + " : (" + cellsList.get(index).getLocation(0) + "," + cellsList.get(index).getLocation(1) + ")"); //Here to test the output
  }

  System.out.println("------------------");

  //Test to see where error lies
  for(int index=0; index < startingCellNumber; index++) {
    System.out.println(index + " : " + cellsList.get(index).getColonyColor() + " : (" + cellsList.get(index).getLocation(0) + "," + cellsList.get(index).getLocation(1) + ")");
  }
}
void draw() {
  //Refresh the background
  background(51);
  //Go through and draw all of the cells (will be moved to the draw function)
  for(Cell activeCell : cellsList) {
    activeCell.drawCell();
    //System.out.println(activeCell);
  }
}

Класс сотовой связи

private int strength;
private int age;
private int reproduction;
private String colonyColor;
private boolean disease;
private int[] location = {0,0};

private String[] directions = {"LEFT","Right","Up","Down"};

class Cell {
  //This is the constructor for the cell class 
  Cell() {
    strength = (int)(Math.random()*8)+3;
    age = 0;
    reproduction = (int)(Math.random()*6)+0;
    colonyColor = pickColor();
    if(colonyColor.equals("BLUE")) { location[0] = (int)(Math.random()*591)+0; location[1] = (int)(Math.random()*391)+0; }
    else if(colonyColor.equals("RED")) { location[0] = (int)(Math.random()*591)+0; location[1] = (int)(Math.random()*391)+0; }
  }
  //This class will randomly pick a team color for the cell
  private String pickColor() {
    int randColorNum = (int)(Math.random()*2)+1;
    if(randColorNum == 1) { return "BLUE"; }
    else if(randColorNum == 2) { return "RED"; }
    else { return "BLUE"; }
  }
  //This method picks the direction in which the cell will move
  private void moveDirection() {
    String chosenDirection = directions[(int)(Math.random()*4)+0];

    if(chosenDirection.equals("Left")) { checkNewLocation(-1,0); }
  }
  //this method uses the direction given by moveDirection() and decides what to do with it
  private void checkNewLocation(int xChange,int yChange) {

  }

  public void drawCell() {
    //Changes color depending on cells colonyColor
    if (getColonyColor().equals("RED")) { fill(255,0,0); }
    else { fill(0,0,255); }
    //Should draw the cell
    //System.out.println(getLocation(0) + " " + getLocation(1));
    rect(getLocation(0), getLocation(1), 10, 10);
  }

  //All of the gets and set methods for the Cell class's variables
  public int getStrength() { return strength; }
  public void setStrength(int s) { strength = s; }
  public int getAge() { return age; }
  public void setAge(int a) { age = a; }
  public int getReproduction() { return reproduction; }
  public void setReproduction(int r) { reproduction = r; }
  public String getColonyColor() { return colonyColor; }
  public void setColonyColor(String c) { colonyColor = c; }
  public boolean getDisease() { return disease; }
  public void setDisease(boolean d) { disease = d; }
  public int getLocation(int index) { return location[index]; }
}

1 Ответ

0 голосов
/ 30 ноября 2018

Проблема с моим кодом заключалась в том, что я создал все переменные класса Cell перед строкой class Cell { }.Перемещая их после строки, все работало нормально.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...