How to get data from an arraylist of objects

0

The problem I'm having is that I want to access the properties of an object that is inside an arraylist.

public float obtenerConsumoCombustibleTrayecto(String marca,String modelo, 
         int anio, float cantidadKMCarretera, float cantidadKMCiudad, 
         int tiempoEspera, int CantidadPersonas)throws AutoNoExiste{

        float Consumo=0;
        float ccar=0f;
        float cciu=0f;


        for(int x=0;x<listaAutos.size();x++){
            Auto a=new Auto(marca , modelo,anio);
            a=listaAutos.get(x);
            if(a.getMarca().equals(marca)){
                if(a.getModelo().equals(modelo)){
                    if(a.getAnio()==anio){
                        ccar=a.getConsumoCarretera();
                        cciu=a.getConsumoCiudad();
                    }
                }
            }
            throw new AutoNoExiste("El auto buscado no se encuentra en el sistema");
            return Consumo;
        }

This is my method but I am not accessing correctly the properties of my objects and I do not understand why.

    
asked by Floppy 16.12.2018 в 22:33
source

1 answer

0

Hello your code should work, unless your list is wrong or another is the error, try replacing this with your for.

 //instancias el objeto auto
  Auto a=new Auto(marca , modelo,anio);
        for(int x=0;x<listaAutos.size();x++){
            //reemplazas el objeto por el iterador
            a=listaAutos.get(x);
            //comparas si un  objeto tiene los parametros que le pasaste
            if(a.getMarca().equals(marca) && a.getModelo().equals(modelo) && a.getAnio()=anio){

               ccar=a.getConsumoCarretera();
               cciu=a.getConsumoCiudad();
                System.out.println("Auto existe  indice "+x);
 }

Notice that your list contains the data, you can fill objects in this way

  ArrayList<Auto> a = new ArrayList<>();
         Auto au = new Auto("Nisan","MO-50",2010,5004,1000,10,8);
          Auto a1 = new Auto("Ford","MO-50",2010,3500,6000,10,8);
         a.add(au);
         a.add(a1);
    
answered by 17.12.2018 в 06:47