add several objects in JAVA

-3

Thank you very much in advance.

How do I do the sum of several objects? For example:

    Ventas producto1 = new Ventas("Leche",14000);
    Ventas producto2 = new Ventas("calaos",800);
    Ventas producto3 = new Ventas("Salchichas",2800);
    Ventas producto4 = new Ventas("Tomate",500);
    Ventas producto5 = new Ventas("pan",200);

It is only necessary to add the values of the products. The expected value in this case would be: 18,300

    
asked by Jorge Leonardo Cardenas Monten 03.11.2018 в 01:44
source

2 answers

-1
System.out.println(producto1.valor + producto2.valor + producto3.valor 
+ producto4.valor + producto5.valor);
    
answered by 03.11.2018 в 05:08
-1

You have to apply object-oriented programming ie your class "Sales" should have something like this:

public class Ventas{
private String producto;
private double precio;

/*
Constructor, al construir se solicita pasar por parametro el nombre del producto y su costo algo como 
lo que ya tienes "Ventas producto5 = new Ventas("pan",200);"*/

public Ventas(String producto, double precio){
 // se hace las asignaciones a las variables locales de lo que recibio
this.producto=producto;
this.precio=precio;
}

/*Y ahora para poder sumar los montos de cada producto se declara un metodo "Get"*/
public double getPrecio(){
return this.precio;
}

}

And now if in the class you are trying to do the addition do the following

public class SumarMontos{
    Ventas producto1 = new Ventas("Leche",14000);
    Ventas producto2 = new Ventas("calaos",800);
    Ventas producto3 = new Ventas("Salchichas",2800);
    Ventas producto4 = new Ventas("Tomate",500);
    Ventas producto5 = new Ventas("pan",200);
    double total=0;

public void sumarMontos(){
total = total + producto1.getPrecio();
total = total + producto2.getPrecio();
total = total + producto3.getPrecio();
total = total + producto4.getPrecio();
total = total + producto5.getPrecio();
}

}

and you will get the total you want in the variable "total" note: I do not recommend copying the code that I have put here since I have not used anything that verifies the syntax.

How to return the summation automatically and add new products? Use your imagination for this we have ArraysList and arrangements you could do the following
public class SumarMontos{
    ArrayList <Ventas> productos = new ArrayList();
    double total=0;
// Cada vez que quieras agregar un nuevo producto ejecutas este metodo
public void agregarNuevoProducto(){
   productos.add(new Ventas("el nombre del nuevo producto",2000));//<- y su precio
}
//Cada vez que quieras saber el total ejecutas este metodo
public void sumarMontos(){
    total = 0;
    for(int i=0;i<productos.size();i++){
      total = total + productos.get(i).getPrecio();
    }
}

}

It's not a scolding but this is basic.

    
answered by 03.11.2018 в 05:23