They left me an exercise about order and product (aggregation), and I don't know how to add Objects stored in an ArrayList. I've tried several things like converting the object to double but the result is always the same, if someone knows how to do it, it would be very helpful, thanks .
import java.util.ArrayList;
public class Orden {
private static int contador;
private int IdOrden;
private ArrayList<Object> productos = new ArrayList<>();
private double total;
public int getIdOrden() {
return IdOrden;
}
public Orden() {
this.IdOrden = ++contador;
}
public void agregarProducto(Object producto) {
try {
productos.add(producto);
}catch(Exception e) {
String errMsg = e.getMessage();
System.out.println(errMsg);
}
}
public double calcularTotal() {
total = 0;
for (Object i:productos) {
System.out.println(i.toString());
total += i.precio;
}
return total;
}
public void mostrardatos() {
System.out.println();
System.out.println("ID_Orden :" + IdOrden);
calcularTotal();
System.out.println("Total :" + total);
}
}
it prints this for me and what I want is to add the prices and print it in total
If you are going to work with class objects
Producto
you do not need to refer to the classObject
, you save yourself having to do a castThe return type of a method is specified in the method declaration. Within the body of the method, the statement is used
return
to return the value.in your case your case your method
calcularTotal
returns adouble
and it should only perform that task calculate the total prices of the products, do not include another print for a debug useas the previous method returns an expected value you must print that value and not the price variable that is declared as 0