NOTA: He publicado la respuesta cuando habías puesto el link, por lo que no vi tu actualización hasta ahora.
Coloca el código que no cumple su trabajo aquí. Primero porque así ayudará a personas que tengan el mismo problema y segundo, porque casi nadie se tomará la molestia de crear un proyecto y agregar las clases y demás que ha descargado.
Por lo que dices aquí supongo que estás trabajando con listas para simular una BBDD, ¿cierto?:
Ok, vamos por partes como dijo Jack el destripador ^^. Primer, creamos un Value Object que representa a un producto:
Luego, creamos el objeto encargado de manejar las consultas e inicializar la lista:
El código entre static {}, se ejecutará cuando el ClassLoader cargue la clase, es decir, se ejecutará de forma simultánea a la compilación. Esto para que la lista de productos esté disponible ni bien ejecutamos la aplicación.
Por último, hacemos pruebas:
Resutados:
Si tienes alguna duda, no dudes en preguntar.
Coloca el código que no cumple su trabajo aquí. Primero porque así ayudará a personas que tengan el mismo problema y segundo, porque casi nadie se tomará la molestia de crear un proyecto y agregar las clases y demás que ha descargado.
Por lo que dices aquí supongo que estás trabajando con listas para simular una BBDD, ¿cierto?:
Citarcantidad de productos de cada tipo.
total de dinero en artículos.
porcentaje de artículos de tipo 2.
Y articulo con el precio mas elevado.
Ok, vamos por partes como dijo Jack el destripador ^^. Primer, creamos un Value Object que representa a un producto:
Código (java) [Seleccionar]
public class ProductVO {
private Integer id;
private String name;
private String description;
private Double price;
private Integer category;
public ProductVO() {}
public ProductVO(Integer id, String name, String description, Double price, Integer category) {
this.id = id;
this.name = name;
this.description = description;
this.price = price;
this.category = category;
}
/*public ProductVO(Object... data) {
for(byte i=0; i<data.length; i++) {
String curObjectClassName = data[i].getClass().getSimpleName();
switch(curObjectClassName.toLowerCase()) {
case "byte": this.id = (Byte) id;
case "string":
switch(i) {
case 1: this.name = (String) data[i]; break;
case 2: this.username = (String) data[i]; break;
case 4: this.category = (String) data[i]; break;
}; break;
case "double": this.price = (Double) price; break;
}
}
}*/
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public Double getPrice() { return price; }
public void setPrice(Double price) { this.price = price; }
public Integer getCategory() { return category; }
public void setCategory(Integer category) { this.category = category; }
}
Luego, creamos el objeto encargado de manejar las consultas e inicializar la lista:
Código (java) [Seleccionar]
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
public class ProductQuery {
private static List<ProductVO> productsList = new ArrayList<>();
static {
Collections.addAll(productsList,
new ProductVO(1, "Cepillo Colgate super", "Cepillo de dientes extra duradero", 18.5d, 1),
new ProductVO(2, "Jarabe para tos", "Jarabe para la tos sabor miel", 25.90d, 2),
new ProductVO(3, "Aspirina", "Pastilla para el dolor de cabeza", 4.3d, 2)
);
}
public int[] getProductExistencesByCategory(int category) {
final int SEARCH_ALL = -1;
final int GROOMING_CATEGORY = 1;
final int MEDICINE_CATEGORY = 2;
int groomingCategoryExistences = 0; // cantidad de productos en aseo personal
int medicineCategoryExistences = 0; // cantidad de productos en medicina
int requestCategoryExistences = 0;
for(ProductVO product : productsList) {
if(category != SEARCH_ALL) {
if(product.getCategory() == category) {
requestCategoryExistences++;
}
} else {
if(product.getCategory() == GROOMING_CATEGORY)
groomingCategoryExistences++;
if(product.getCategory() == MEDICINE_CATEGORY)
medicineCategoryExistences++;
}
}
if(category != SEARCH_ALL)
return new int[] { requestCategoryExistences };
else
return new int[] {groomingCategoryExistences, medicineCategoryExistences};
}
public Double getTotalAmountOfProducts() {
Double totalAmount = 0d;
for(ProductVO product : productsList) {
totalAmount += product.getPrice();
}
return totalAmount;
}
public ProductVO getMostValuedProduct() {
ProductVO mostValued = productsList.get(0);
for(ProductVO product : productsList) {
if(product.getPrice() > mostValued.getPrice())
mostValued = product;
}
return mostValued;
}
}
El código entre static {}, se ejecutará cuando el ClassLoader cargue la clase, es decir, se ejecutará de forma simultánea a la compilación. Esto para que la lista de productos esté disponible ni bien ejecutamos la aplicación.
Por último, hacemos pruebas:
Código (java) [Seleccionar]
public class ProductsTest{
public static void main(String []args){
ProductQuery query = new ProductQuery();
int[] categoryExistences = query.getProductExistencesByCategory(-1);
int[] medicineCategoryExistences = query.getProductExistencesByCategory(2);
ProductVO mostValuedProduct = query.getMostValuedProduct();
Double totalAmount = query.getTotalAmountOfProducts();
System.out.println("Products existences by category: ");
printArray(categoryExistences);
System.out.println("Products existences by medicine category: ");
printArray(medicineCategoryExistences);
System.out.println("Most valued product: "+mostValuedProduct.getName());
System.out.println("Total amount of products: "+totalAmount);
}
public static void printArray(int[] array) {
for(int value : array)
System.out.println(value);
}
}
Resutados:
Código [Seleccionar]
Products existences by category:
1
2
Products existences by medicine category:
2
Most valued product: Jarabe para tos
Total amount of products: 48.699999999999996
Si tienes alguna duda, no dudes en preguntar.