对存储在ArrayList(Java)中的对象的所有双值求和

时间:2017-05-09 01:13:54

标签: java arraylist

我有一个包含对象的ArrayList。每个对象都有3个值:String name,double price,int quantity。如何编写将所有对象的总和相加并打印结果的方法。并且如果int数量> 1,则价格将乘以数量。

到目前为止我写的代码:

产品类

public class Product {

private String name;
private double price;
private int quantity;

public Product(String name, double price, int quantity) {
    this.name = name;
    this.price = price;
}

public String getName() {
    return name;
}

public double getPrice() {
    return price;
}

public static Product createProduct(String name, double price, int quantity){
    return new Product(name, price, quantity);
}  
}

产品清单类

import java.util.ArrayList;
import java.util.List;

public class ProductList {

private String name;

List<Product> newList;

public ProductList(String name) {
    this.name = name;
    this.newList = new ArrayList<>();
}

public boolean addNewProduct(Product product) {
    if (findProduct(product.getName()) >= 0) {
        System.out.println("Product is already on the list");
        return false;
    }
    newList.add(product);
    return true;
}

public boolean removeProduct(Product product) {
    if (findProduct(product.getName().toUpperCase()) < 0) {
        System.out.println("Product not found");
        return false;
    }
    newList.remove(product);
    return true;
}

private int findProduct(String productName) {
    for (int i = 0; i < newList.size(); i++) {
        Product product = newList.get(i);
        if (product.getName().equals(productName)) {
            return i;
        }
    }
    return -1;
}

public Product queryProduct(String name) {
    int position = findProduct(name);
    if (position >= 0) {
        return this.newList.get(position);
    }
    return null;
}

public double sumProducts() {
    double sum = 0;
    for (int i = 0; i < newList.size(); i++) {
        sum += newList.get(i).getPrice();
    }
    return sum;
}

/*public boolean listProducts(){};

public boolean updateProduct(){};
*/

}

模拟课程:

public class Simulation {

private static Scanner scanner = new Scanner(System.in);
private static ProductList myProductList = new ProductList("My list");

private static void addNewProduct() {
    System.out.println("Enter new product name: ");
    String name = scanner.nextLine();
    System.out.println("Enter new product price: ");
    double price = scanner.nextDouble();
    System.out.println("Enter new product quantity");
    int quantity = scanner.nextInt();
    Product newProduct = Product.createProduct(name, price, quantity);
    if (myProductList.addNewProduct(newProduct) == true) {
        System.out.println("New product added: " + name + " | price: " + price + " | quantity: " + quantity);
    }
}

private static void removeProduct() {
    System.out.println("Enter product name: ");
    String name = scanner.nextLine().toUpperCase();
    Product existingProduct = myProductList.queryProduct(name);
    if (existingProduct == null) {
        System.out.println("No such product");
        return;
    }
    if (myProductList.removeProduct(existingProduct)) {
        System.out.println("Sucessfully deleted product: " + existingProduct.getName());
    } else {
        System.out.println("Error deleting");
    }

}

private static void printActions() {
    System.out.println("Avaiable actions");
    System.out.println("press: ");
    System.out.println("0 - to shut down\n" +
            "1 - to add new product\n" +
            "2 - to remove product\n" +
            "3 - to sum all products");
}

private static void sumProducts(){
    myProductList.sumProducts();
}


public static void main(String[] args) {

    printActions();

    boolean quit = false;
    while (!quit)
        try {
            System.out.println("\nEnter action: ");
            int action = scanner.nextInt();
            scanner.nextLine();
            switch ((action)) {
                case 0:
                    System.out.println("\nShutting down...");
                    quit = true;
                    break;
                case 1:
                    addNewProduct();
                    break;
                case 2:
                    removeProduct();
                    break;

            }

        } catch (InputMismatchException e) {
            System.out.println("Bad key pressed, only values form 0 to 2 accepted");
            scanner.nextLine();
        }

}

}

提前致谢

3 个答案:

答案 0 :(得分:0)

每个产品的总和缺失乘以其数量。

public double sumProducts() {
    double sum = 0;
    for (int i = 0; i < newList.size(); i++) {
        Product product = newList.get(i);
        sum += product.getPrice() * product.getQuantity();
    }
    return sum;
}

答案 1 :(得分:0)

您可以使用Java 8在一行中完成。

public double sumProducts() { 
    return newList.stream().mapToDouble(product -> product.getPrice() * product.getQuantity()).sum();
}

答案 2 :(得分:0)

如果您使用double存储价格,则在尝试添加和乘以值时,您将得到错误的答案。例如,0.1 + 0.2double不同0.3。如果要对十进制数进行精确算术运算,则应使用BigDecimal类代替double。如果你不这样做,我可以保证你的程序有时会给出错误的答案。

因此,您需要按照以下方式更改Product课程。

public class Product {

    private String name;
    private BigDecimal price;
    private int quantity;

    public Product(String name, BigDecimal price, int quantity) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public static Product createProduct(String name, BigDecimal price, int quantity){
        return new Product(name, price, quantity);
    }  
}

您还需要在调用此类方法的代码中进行相应的更改。

完成后,您可以使用BigDecimal类的方法进行算术运算。它可能看起来像这样。

public BigDecimal calculateTotalPrice() {
    BigDecimal total = BigDecimal.ZERO;
    for (Product product : newList) {
        BigDecimal linePrice = product.getPrice().multiply(new BigDecimal(product.getQuantity()));
        total = total.add(linePrice);
    }
    return total;
}