简体   繁体   中英

How do I save ArrayLists with different names in a while loop?

I'm kinda stuck in a java project. I have this issue and i don't know how to work this out.

Basically i create a robot wich go from object to object listing them. Objects don't move but robots (agents in my code) do.

Some of the variables i use come from the FinalProject Class wich is my main class.

I create a matrix of ArrayLists as my world and i want to add objects and agents to it. They both henerit from the class Entity. My problem is I dont know how to name them differently as I add them to the matrix. Here's my World class:

package finalproject;
import java.util.*;

public class World {
protected int cord_x , cord_y , agent_num , object_num , numero_x , numero_y, conta = 1, i = 0;
protected String op, nome;
protected String [] tipos;

public World (int cord_x, int cord_y, int agent_num, int object_num , String op){
    this.cord_x = cord_x;
    this.cord_y = cord_y;
    this.agent_num = agent_num;
    this.object_num = object_num;
    this.op = op;
    ArrayList<Entity>[][] mundo = (ArrayList<Entity>[][])new ArrayList<?>[cord_x][cord_y];
    if (op.equals("s")){
        gera_agent(agent_num , mundo);
        gera_object(object_num, mundo);
    }
}

private ArrayList<Entity>[][] gera_agent(int num , ArrayList<Entity>[][] mundo){
    String [] cores = {"vermelho", "azul", "verde", "preto"};
    String [] formas = {"triangulo", "quadrado", "retangulo", "losango"};
    String [] estrategias = {"random", "hamming", "closest"};
    i=0;
    while (i<num){
        int numeroY = new Random().nextInt(cord_x);
        int numeroX = new Random().nextInt(cord_y);
        int rcores = new Random().nextInt(cores.length);
        int rformas = new Random().nextInt(formas.length);
        int restrategias = new Random().nextInt(estrategias.length);

        String cor = (cores[rcores]);
        String forma = (formas[rformas]);
        String estrategia = (estrategias[restrategias]);
        nome = "Agente" + Integer.toString(conta);
        Entity nome = new Agent(nome, cor, forma, numeroX, numeroY, conta, estrategia, FinalProject.raio);
        mundo[numeroX][numeroY].add(nome);
        conta++;
        i++;
    }
    return mundo;
}

private ArrayList<Entity>[][] gera_object(int num , ArrayList<Entity>[][] mundo){
    String [] cores = {"vermelho", "azul", "verde", "preto"};
    String [] formas = {"triangulo", "quadrado", "rectangulo", "losango"};

    if (FinalProject.op1.equals("planeta")){
        tipos = new String[] {"rocha", "alien", "caratera"};
    }
    else if (FinalProject.op1.equals("catastrofe")){
        tipos =  new String []{"sobrevivente", "morto", "escombros"};
    }
    else if (FinalProject.op1.equals("domesticos")){
        tipos = new String [] {"mesa", "cadeira", "vassora"};
    }

    i=0;
    while (i<num){
        int numeroX = new Random().nextInt(cord_x);
        int numeroY = new Random().nextInt(cord_y);

        int rcores = new Random().nextInt(cores.length);
        int rformas = new Random().nextInt(formas.length);
        int rtipo;
        rtipo = new Random().nextInt(tipos.length);
        String cor = (cores[rcores]);
        String forma = (formas[rformas]);
        String tipo = (tipos[rtipo]);
        nome = "Object" + Integer.toString(conta);
        Entity nome = new Object(nome, cor, forma, numeroX, numeroY, conta, estrategia, FinalProject.raio);
        mundo[numeroX][numeroY].add(nome);
        conta++;
        i++;

    }
    return mundo;
}

Basically when i am doing this: Entity nome = new Agent(nome, cor, forma, numeroX, numeroY, conta, estrategia, FinalProject.raio); mundo[numeroX][numeroY].add(nome); - which is stupid. Do i need to name the object i wanna add in the matrix? if i do, how do i do it?

at some point in my name i create the world using some input variables this way:

World mundo = new World(W_x , W_y , num_ag , num_ob , op2);

My Entity Class:

package finalproject;
import java.util.ArrayList;

public abstract class  Entity {
    protected String name;
    protected String color;
    protected String shape;
    protected int xCoordenate;
    protected int yCoordenate;
    protected int id;
    public Entity (String name, String color , String shape , int xCoordenate , int yCoordenate , int id){
        this.name = name;
        this.color = color;
        this.shape = shape;
        this.xCoordenate = xCoordenate;
        this.yCoordenate = yCoordenate;
        this.id = id;
    }

I think the problem in your code is that you are not initializing the ArrayList before it's use eg One I have written in the snippet below:: mundo[i][j] = new ArrayList<Integer>();

     int cord_x = 6, cord_y = 5, num = 10;
     ArrayList<Integer>[][] mundo = (ArrayList<Integer>[][])
                                             new ArrayList<?>[cord_x][cord_y];
     for(int i = 0; i < cord_x; i++){
         for(int j = 0; j < cord_y; j++){

             //***Instantiate the ArrayList---This is required***
             mundo[i][j] = new ArrayList<Integer>(); 
             for(int k = 0; k < num; k++){
                 // Add the elements in the array list
                 mundo[i][j].add(new Integer(i+j+k)); 
             }
         }
     }

     //Check the elements
     for(int i = 0; i < cord_x; i++){
         for(int j = 0; j < cord_y; j++){
             for(int k = 0; k < num; k++){
                 // prints the elements
                 System.out.println("mundo["+i+"]["+j+"]- place "
                      +k+" Element == " +mundo[i][j].get(k)); 
             }
         }
     }

The above snippet populates the elements the first iteration and prints them in the second as:

mundo[0][0]- place 0 Element == 0
mundo[0][0]- place 1 Element == 1
mundo[0][0]- place 2 Element == 2
mundo[0][0]- place 3 Element == 3
......

I think you can adapt two approaches in your code.

  1. Before mundo[numeroX][numeroY].add(nome); line add a check to see initialization as below

     if(mundo[numeroX][numeroY] == null){ mundo[numeroX][numeroY] = new ArrayList<Entity>(); } 
  2. Before the while loop, you can initialize all the array list elements together by putting a initialization snippet as below:

      for(int i = 0; i < cord_x; i++){ for(int j = 0; j < cord_y; j++){ mundo[i][j] = new ArrayList<Entity>(); // <-- Instantiate the ArrayList } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM